In this blog, we will see how to create a product attribute in Magento 2.
Magento 2 manages Product by EAV model, so we can’t just add an attribute for the product by adding a column for the product table.
Before we proceed we hope you should know about the Install/Upgrade script.
If you have already created an install script then you need to increase the version of your file under etc/module.xml.
If your version is 1.0.0 then increased it like 1.0.1
Ok, now we will ready to creating a product attribute. First, we need to create EavSetup object using a factory. To do that just create a public method __construct and inject Magento\Eav\Setup\EavSetup class in it.
Now, we need to get a new EavSetup instance and use addAttribute() method to create a new attribute.
Step 1: Now create UpgradeData.php in the following path:
app/code/Yournamespace/Yourmodule/Setup
<?php
namespace Yournamespace\Yourmodule\Setup;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class UpgradeData implements UpgradeDataInterface
{
private $eavSetupFactory;
public function __construct(EavSetupFactory $eavSetupFactory)
{
$this->eavSetupFactory = $eavSetupFactory;
}
public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'attribute_code', // Here, you need to specify attribute code
[
'group' => 'Product Details',
'type' => 'varchar',
'backend' => '',
'frontend' => '',
'label' => 'Attribute Code', // Define attribute label
'input' => 'select',
'class' => '',
'source' => '',
'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
'visible' => true,
'required' => false,
'user_defined' => true,
'default' => '',
'searchable' => true,
'filterable' => true,
'comparable' => false,
'visible_on_front' => true,
'used_in_product_listing' => true,
'unique' => false,
'apply_to' => 'simple,grouped,virtual,bundle,downloadable,configurable'
]
);
}
}
As you can see into the code, the addAttribute method needs to the type id, name of the attribute as well as we need to define such as group, input type, source, label, apply_to, etc.
Now just RUN the below command to RUN your upgrade script.
php bin/magento setup:upgrade
After RUN above code your attribute will be created and now run below command.
php bin/magento setup:static-content:deploy
Now, go Logging to the admin panel > Products > Catalog > Open any product you can see your created attribute in the specific group.
Thanks for reading this post.