Can Yildirim's Blog

How to add EAV attributes to products by setup scripts | #MagentoTips3

August 27, 2021

While EAV attributes can be managed by admin it can also be put in setup scripts and be ready with the deployment without any manual operation. This is useful especially if you deploy your code couple of different environment as you wouldn’t want to go and manually add attributes for each environment.

To add an attribute to a product we would need to understand EAV Attributes and Data Patches

It can be done in three simple step:

  • Create PHP Class under <your module>/Setup/Patch/Data
  • Add implements DataPatchInterface to your class, that’ll bring required function
  • Implement apply as following
class AddStrengthAttribute implements DataPatchInterface{ public function apply(){ // add eavSetupFactory(Magento\Eav\Setup\EavSetupFactory) to constructor $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]); $eavSetup->addAttribute( 'catalog_product', 'colour', [ 'label' => 'Colour', 'type' => 'int', 'input' => 'select', 'required' => false, 'user_defined' => true, 'global' => ScopedAttributeInterface::SCOPE_GLOBAL, 'visible' => true, 'filterable' => true, 'searchable' => true, 'comparable' => false, 'filterable_in_search' => true, 'used_for_promo_rules' => true, 'used_in_product_listing' => true, 'unique' => false, 'option' => [ 'values' => [ 'Orange', 'Black', 'Blue', 'Red' ] ], ] ); // we should add product to a attribute set $eavSetup->addAttributeToGroup( Product::ENTITY, 'attribute_set_name', 'Product Details', 'colour' ); } // This may be required as current data patch may need other dependant data patches to run public static function getDependencies() { return [DependentClassName::class]; } // This is rarely used. Gets aliases (previous names) for the patch. public function getAliases() { return []; } }

Follow : @DailyMagento


Can Yildirim

Written by Can Yildirim who lives in London. Full Stack Software Engineer. Follow me on Twitter Linkedin

© 2023,