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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
<?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!