In this blog, we will see How to create catalog product attributes programmatically in just one step.
Magento 2 uses the EAV model so we can’t add an attribute by adding the column in the product table.
Quick Tip:- Top 10 Effective Magento SEO Tips
I assume that you already know about Install/Upgrade scripts because we will use the InstallData script to create an attribute.
Step 1: Create InstallData.php file in the following location
app/code/[Namespace]/[Module]/Setup/InstallData.php
<?php
namespace [Namespace]\[Module]\Setup;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
private $eavSetupFactory;
public function __construct(EavSetupFactory $eavSetupFactory)
{
$this->eavSetupFactory = $eavSetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'enable',
[
'type' => 'int',
'backend' => '',
'frontend' => '',
'label' => 'Enable',
'input' => 'select',
'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' => false,
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => true,
'unique' => false,
'apply_to' => 'simple,grouped,virtual,bundle,downloadable,configurable'
]
);
}
}
As you can see in the above code:
We have created the attribute which is for selection like Yes/No.
That’s why we use the source as “Magento\Eav\Model\Entity\Attribute\Source\Boolean” and if you want selection field then you must need to input type as select.
Using creating attributes programmatically you can also able to make the field as require or optional.
Sometimes, we only need to show attributes in a specific product, not on all products that you can do with the “apply_to” property as you can see in the above code.