Magento has two types of attributes that can be used to provide extra functionalities, i.e., Eav attributes and extension attributes. Here I am going to discuss the eav attributes and show how to add eav attribute for the product in Magento 2.
Entry attribute value (eav) attributes are the attributes added by the merchant from the admin panel to describe the products. Properties such as shape, size, etc. are described using custom or eav attributes.
To add Eav attribute for the Product in Magento 2, one needs to follow certain steps. I have tried to simplify the process below:
Step 1: Declare EAV setup factory
/** * @var EavSetupFactory */ protected $eavSetupFactory; /** * UpgradeData constructor * * @param EavSetupFactory $eavSetupFactory */ public function __construct(EavSetupFactory $eavSetupFactory) { $this->eavSetupFactory = $eavSetupFactory; }
Step 2: Add attribute
/** @var EavSetup $eavSetup */ $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); /** * Add attributes to the eav/attribute */ $eavSetup->addAttribute( \Magento\Catalog\Model\Product::ENTITY, 'is_featured', [ 'group' => 'General', 'type' => 'int', 'backend' => '', 'frontend' => '', 'label' => 'Is Featured', 'input' => 'boolean', 'class' => '', 'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean', 'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL, 'visible' => true, 'required' => false, 'user_defined' => false, 'default' => '1', 'searchable' => false, 'filterable' => false, 'comparable' => false, 'visible_on_front' => false, 'used_in_product_listing' => false, 'unique' => false, 'apply_to' => '' ] );
Here,
- is_featured: attribute code
- group: group name for attribute that will display in backend
- type: data type save in database
- global: the scope of attribute (store, website or global)
- visible_on_frontend: true or false that allow the attribute is displayed on frontend or no
- apply_to: product type that you want to add attribute
Step 3: Remove an EAV attribute for the product
$entityTypeId = 4; // Find these in the eav_entity_type table $eavSetup->removeAttribute($entityTypeId, 'is_featured');
Follow the above steps and easily add EAV attribute to the product in Magento 2!
I tried to present an easy way for the task and hope it helps. Please comment below if any problem is faced while implementing the above steps.
Review my blog and flash 5 stars if found useful!
Happy coding