Magento supports two types of attributes including EAV attributes and extension attributes that provide extra functionalities for your stores. In this post, you will get an overview about EAV attributes and detailed instruction in how to add EAV attribute in Magento 2.
Construct function is must for EAV attribute add to controller
public function __construct(
\Magento\Eav\Model\Entity\Context $context,
$data = []
) {
parent::__construct($context, $data);
$this->setType('entity_type_code');
$this->setConnection('entity_type_code_read', 'entity_type_code_write');
}
Setting EAV attribute for product Magento 2
/**
* @var EavSetupFactory
*/
protected $eavSetupFactory;
/**
* UpgradeData constructor
*
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(EavSetupFactory $eavSetupFactory)
{
$this->eavSetupFactory = $eavSetupFactory;
}
Add EAV 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' => ''
]
);
type can be like=> varchar to store (letters and names)
=>int to store(numbers)
=>select can be used for select box and insert values through ‘option’ => “values” attribute.