In this blog, we are going to show you how to create a product attribute using the latest Declarative
Schema “data patch “.
A Data patch is a class that stores instructions for data modification. Using a data patch we can add custom product attributes in Magento 2 by creating a PHP file.
Once you Create the file AddCustomProductAttribute.php in this directory . app/code/VenderName/ModuleName/ Setup/Patch/Data/. and paste the below code :
AddCustomProductAttribute.php
<?php
namespace VenderName\ModuleName\Setup\Patch\Data;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
class AddCustomProductAttribute implements DataPatchInterface
{
protected $_eavSetupFactory;
protected $_moduleDataSetup;
/**
* @param ModuleDataSetupInterface $_moduleDataSetup
*/
public function __construct(
EavSetupFactory $_eavSetupFactory,
ModuleDataSetupInterface $_moduleDataSetup
){
$this->eavSetupFactory = $_eavSetupFactory;
$this->_moduleDataSetup = $_moduleDataSetup;
}
public function apply()
{
$eavSetup = $this->eavSetupFactory->create(array('setup' => $this->_moduleDataSetup));
$eavSetup->addAttribute(
\Magento\Catalog\Model\Product::ENTITY,
'indexfollow_enable',
array(
'group' => 'Index Follow',
'type' => 'text',
'backend' => '',
'frontend' => '',
'label' => 'Enable Index Follow',
'input' => 'boolean',
'class' => 'indexfollow_enable',
'source' => \Magento\Eav\Model\Entity\Attribute\Source\Boolean::class,
'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
'visible' => true,
'required' => false,
'user_defined' => true,
'default' => '',
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => true,
'unique' => false,
)
);
}
/**
* {@inheritdoc}
*/
public static function getDependencies()
{
return array();
}
/**
* {@inheritdoc}
*/
public function getAliases()
{
return array();
}
/**
* {@inheritdoc}
*/
public static function getVersion()
{
return ‘1.0.0'}
}
after will running the below command :
- php -dmemory_limit=2G bin/magento setup:upgrade
- php -dmemory_limit=2G bin/magento setup:static-content:deploy -f -j
- php -dmemory_limit=2G bin/magento cache:flush
Now, you can see in the eav_attribute table that your custom product attribute was created successfully using the data patch.
If you have any questions let me know in the comment section.
Thank you!







Leave a Reply