Magento 2.3: Как создать атрибут продукта с помощью декларативной схемы?


Как создать атрибут продукта в Magento 2.3 с помощью декларативной схемы. Я попробовал приведенный ниже код, но элемент ввода не отображается в форме.

<?php

namespace Rokanthemes\Updates\Setup\Patch\Data;

use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\Patch\PatchVersionInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\DB\Ddl\Table;

class AddAttributes implements DataPatchInterface
{
    protected $_moduleDataSetup;
    protected $_customerSetupFactory;
    protected $_attributeSetFactory;

    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        CustomerSetupFactory $customerSetupFactory,
        AttributeSetFactory $attributeSetFactory
    )
    {
        $this->_moduleDataSetup = $moduleDataSetup;
        $this->_customerSetupFactory = $customerSetupFactory;
        $this->_attributeSetFactory = $attributeSetFactory;
    }

    public function apply()
    {
        $customerSetup = $this->_customerSetupFactory->create(['setup' => $this->_moduleDataSetup]);

        $customerEntity = $customerSetup->getEavConfig()->getEntityType(Customer::ENTITY);
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

        $attributeSet = $this->_attributeSetFactory->create();
        $attributeSet->getDefaultGroupId($attributeSetId);

        $customerSetup->addAttribute(Customer::ENTITY, 'news_from_date', array(
            'type' => Table::TYPE_DATE,
            'label' => 'New from date',
            'input' => 'date',
            'required' => 1,
            'type' => 'static',            
            'visible' => true
        ));
    }

    public function getAliases()
    {
        return [];
    }

    public static function getDependencies()
    {
        return [

        ];
    }
}

Спасибо за помощь.

Author: Rafael Corrêa Gomes, 2019-03-01

2 answers

Я написал об этом целый пост в блоге. Она довольно обширна и подробно описывает все тонкости: https://markshust.com/2019/02/19/create-product-attribute-data-patch-magento-2.3-declarative-schema/

Тем не менее, вот последний класс кода, с которым вы можете работать:

<?php
namespace Acme\Foo\Setup\Patch\Data;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;

class AddAlternativeColorAttribute implements DataPatchInterface
{
    /** @var ModuleDataSetupInterface */
    private $moduleDataSetup;

    /** @var EavSetupFactory */
    private $eavSetupFactory;

    /**
     * @param ModuleDataSetupInterface $moduleDataSetup
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        EavSetupFactory $eavSetupFactory
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function apply()
    {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);

        $eavSetup->addAttribute('catalog_product', 'alternative_color', [
            'type' => 'int',
            'label' => 'Alternative Color',
            'input' => 'select',
            'used_in_product_listing' => true,
            'user_defined' => true,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public static function getDependencies()
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public function getAliases()
    {
        return [];
    }
}
 12
Author: Mark Shust at M.academy, 2019-03-18 19:54:38

Подход к исправлению данных применяется после версии Magento 2.3.x. Таким образом, вы можете использовать исправление данных для добавления или обновления данных в таблице базы данных.

Вам нужно создать CreateCustomAttr.php файл внутриприложение/код/Имя поставщика/Имя модуля/Настройка/Исправление/Данные/

Добавьте это ниже кода внутри CreateCustomAttr.php файл

Ссылка: https://www.rohanhapani.com/magento-2-create-a-product-attribute-using-data-patches/

<?php

declare (strict_types = 1);

namespace VendorName\ModuleName\Setup\Patch\Data;

use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;

class CreateCustomAttr implements DataPatchInterface {


    private $moduleDataSetup;


    private $eavSetupFactory;


    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        EavSetupFactory $eavSetupFactory
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function apply() {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);

        $eavSetup->addAttribute('catalog_product', 'news_from_date', [
            'type' => 'text',
            'backend' => '',
            'frontend' => '',
            'label' => 'News From Date',
            'input' => 'text',
            'class' => '',
            'source' => '',
            'global' => ScopedAttributeInterface::SCOPE_GLOBAL,
            'visible' => true,
            'required' => true,
            'user_defined' => false,
            'default' => '',
            'searchable' => false,
            'filterable' => false,
            'comparable' => false,
            'visible_on_front' => false,
            'used_in_product_listing' => true,
            'unique' => false,
            'apply_to' => '',
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public static function getDependencies() {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public function getAliases() {
        return [];
    }
}
 0
Author: Ankita Patel, 2020-05-28 06:42:47