Hello Guys! 👋
Magento 2 managed product by EAV model. EAV Stands for Entity-Attribute-Value. So if we want to add attributes to a product then we can’t simply add a column to the product table.
So we need to follow the following way to add custom product attributes in our store.
Now Magento 2 does not support the old setup data method to add attributes so we need to follow the data patch method to add product attributes.
The following code is helpful for creating custom product attributes using DataPatch.
Step 1: Add ProductAttribute.php file in following path
app\code\Vendor\Extension\Setup\Patch\Data
<?php
namespace Vendor\Extension\Setup\Patch\Data;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
class ProductAttribute implements DataPatchInterface
{
/** @var ModuleDataSetupInterface */
private $moduleDataSetup;
/** @var EavSetupFactory */
private $eavSetupFactory;
/**
* @param ModuleDataSetupInterface $moduleDataSetup
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(
ModuleDataSetupInterface $moduleDataSetup,
EavSetupFactory $eavSetupFactory
) {
$this->moduleDataSetup = $moduleDataSetup;
$this->eavSetupFactory = $eavSetupFactory;
}
/**
* {@inheritdoc}
*/
public function apply()
{
/** @var EavSetup $eavSetup */
$eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
$eavSetup->addAttribute('catalog_product', 'custom-attribute', [
'type' => 'int',
'backend' => '',
'frontend' => '',
'label' => 'Custom Attribute',
'input' => 'select',
'class' => '',
'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
'global' => ScopedAttributeInterface::SCOPE_GLOBAL,
'visible' => true,
'required' => false,
'user_defined' => true,
'default' => 0,
'visible_on_front' => false,
'used_in_product_listing' => true,
'unique' => false,
'apply_to' => '',
]);
}
/**
* {@inheritdoc}
*/
public static function getDependencies()
{
return [];
}
/**
* {@inheritdoc}
*/
public function getAliases()
{
return [];
}
}
After this run php bin/magento setup:upgrade command from magento2 cli
Hope! It will help you
Thank you 😊
