We use cookies to make your experience better. To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies. Learn more.
Magento 2 – Add Product Attribute with Code
1: Create the Setup File:
Create theInstallData.php file in app/code/Vendor/Module/Setup/Patch/Data with the following content:
<?php
namespace Vendor\Module\Setup\Patch\Data;
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;
use Magento\Catalog\Model\Product;
class InstallData implements InstallDataInterface
{
private $eavSetupFactory;
public function __construct(EavSetupFactory $eavSetupFactory)
{
$this->eavSetupFactory = $eavSetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
/** @var EavSetup $eavSetup */
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(
Product::ENTITY,
'custom_attribute',
[
'type' => 'varchar',
'label' => 'Custom Attribute',
'input' => 'text',
'required' => false,
'sort_order' => 100,
'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
'visible' => true,
'user_defined' => true,
'default' => '',
'group' => 'General',
'backend' => '',
]
);
}
}
Customization Options
type: The data type of the attribute (e.g.,varchar,int,text,decimal).input: The input type for the attribute (e.g.,text,textarea,select,multiselect,boolean,date).backend: If you need to define custom backend models for processing the attribute data, specify it here.source: If the attribute is a dropdown or multiselect, you can specify a source model here to provide the options.