Add product Attribute via DataPatch

Reference links to understand DataPatch


Create your file: {Vendor_Name}\{Module_Name}\Setup\Patch\Data\{AddAttrbiute} . In directory is your file name, you can place with any name, it will compare with table “patch_list” and add your data. That file only run one time


Your class should implement

 class AddAttrbiute implements Magento\Framework\Setup\DataPatchInterface;

Use dependency:

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
public function __construct(
   ModuleDataSetupInterface $moduleDataSetup,
   EavSetupFactory $eavSetupFactory
) {
   $this->moduleDataSetup = $moduleDataSetup;
   $this->eavSetupFactory = $eavSetupFactory;
}

You must implement 3 function: apply(), getDependencies(), getAliases(). Function apply() is main function like function execute.


Use eavSetup to addAttribute:

public function apply()
    {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
        $eavSetup->removeAttribute(\Magento\Catalog\Model\Product::ENTITY,'use_tabs_ordercombine');
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'use_tabs_ordercombine',
            [
                'type' => 'varchar',
                'label' => 'Select Category OrderCombine',
                'input' => 'select',
                'required' => false,
                'sort_order' => 9999,
                'group' => 'General',
                'source' => 'Magento\Catalog\Model\Product\Attribute\Source\Status'
            ]
        );
    }
    /**
     * {@inheritdoc}
     */
    public static function getDependencies()
    {
        return [];
    }

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

Finally, run upgrade command to implement that attribute to your site:

php bin/magento setup:upgrade --keep-generated

Leave a Reply