Magento, Magento 2

Magento 2 : Create a Customer Attribute using Data Patches

Magento 2 Create a Customer Attribute using Data Patches

In this tutorial, Today I will explain to how to create a customer attribute using data patches in Magento 2. From Magento 2.3.x, Magento brings new features which is  data patches. The Data Patch is class that contains data notification instruction.

Previously, Magento 2 uses InstallData and UpgradeData file use add data in core table or custom table. From Magento 2.3 it will be replaced by Data Patch.

How to Add Data Patch in Magento 2.3 :

It’s defined in <Vendor_Name>/<Module_Name>/Setup/Patch/Data/<Patch_File_Name>.php and it will implement \Magento\Setup\Model\Patch\DataPatchInterface interface.

So, Let’s follow the steps :

You may also like this :

Steps of How to Create Customer Attribute using Data Patch in Magento 2 :

1) First of all, Let’s assume that you have created simple module. Now, To create customer attribute Create CustomerAttribute.php file at app/code/RH/Helloworld/Setup/Patch/Data/  and paste the below code :

<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

/**
 * Created By : Rohan Hapani
 */
declare (strict_types = 1);

namespace RH\Helloworld\Setup\Patch\Data;

use Magento\Catalog\Ui\DataProvider\Product\ProductCollectionFactory;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Config;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\Patch\PatchRevertableInterface;
use Psr\Log\LoggerInterface;

/**
 * Class CustomerAttribute for Create Customer Attribute using Data Patch.
 * @package RH\Helloworld\Setup\Patch\Data
 */
class CustomerAttribute implements DataPatchInterface, PatchRevertableInterface
{
   /**
    * @var ModuleDataSetupInterface
    */
   private $moduleDataSetup;

   /**
    * @var EavSetupFactory
    */
   private $eavSetupFactory;
   
   /**
    * @var ProductCollectionFactory
    */
   private $productCollectionFactory;
   
   /**
    * @var LoggerInterface
    */
   private $logger;
   
   /**
    * @var Config
    */
   private $eavConfig;
   
   /**
    * @var \Magento\Customer\Model\ResourceModel\Attribute
    */
   private $attributeResource;

   /**
    * CustomerAttribute Constructor
    * @param EavSetupFactory $eavSetupFactory
    * @param Config $eavConfig
    * @param LoggerInterface $logger
    * @param \Magento\Customer\Model\ResourceModel\Attribute $attributeResource
    * @param \Magento\Framework\Setup\ModuleDataSetupInterface $moduleDataSetup
    */
   public function __construct(
       EavSetupFactory $eavSetupFactory,
       Config $eavConfig,
       LoggerInterface $logger,
       \Magento\Customer\Model\ResourceModel\Attribute $attributeResource,
       \Magento\Framework\Setup\ModuleDataSetupInterface $moduleDataSetup
   ) {
       $this->eavSetupFactory = $eavSetupFactory;
       $this->eavConfig = $eavConfig;
       $this->logger = $logger;
       $this->attributeResource = $attributeResource;
       $this->moduleDataSetup = $moduleDataSetup;
   }

   /**
    * {@inheritdoc}
    */
   public function apply()
   {
       $this->moduleDataSetup->getConnection()->startSetup();
       $this->addPhoneAttribute();
       $this->moduleDataSetup->getConnection()->endSetup();
   }

   /**
    * @throws \Magento\Framework\Exception\AlreadyExistsException
    * @throws \Magento\Framework\Exception\LocalizedException
    * @throws \Zend_Validate_Exception
    */
   public function addPhoneAttribute()
   {
       $eavSetup = $this->eavSetupFactory->create();
       $eavSetup->addAttribute(
           \Magento\Customer\Model\Customer::ENTITY,
           'phone_number',
           [
               'type' => 'varchar',
               'label' => 'Mobile Number',
               'input' => 'text',
               'required' => 1,
               'visible' => 1,
               'user_defined' => 1,
               'sort_order' => 999,
               'position' => 999,
               'system' => 0
           ]
       );

       $attributeSetId = $eavSetup->getDefaultAttributeSetId(Customer::ENTITY);
       $attributeGroupId = $eavSetup->getDefaultAttributeGroupId(Customer::ENTITY);

       $attribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'phone_number');
       $attribute->setData('attribute_set_id', $attributeSetId);
       $attribute->setData('attribute_group_id', $attributeGroupId);

       $attribute->setData('used_in_forms', [
           'adminhtml_customer',
           'adminhtml_customer_address',
           'customer_account_edit',
           'customer_address_edit',
           'customer_register_address',
           'customer_account_create'
       ]);

       $this->attributeResource->save($attribute);
   }

   /**
    * {@inheritdoc}
    */
   public static function getDependencies()
   {
       return [];
   }

   /**
    *
    */
   public function revert()
   {
   }

   /**
    * {@inheritdoc}
    */
   public function getAliases()
   {
       return [];
   }
}

Here, In this above file there are some new functions available in that file code. So, Let’s understand short details about the use of that functions.

First of all, apply() function is use to implement code logic to installing or upgrading data to the database. For ex, here you can see that there are create product attribute code logic apply inside apply() function.

After that, getAliases() function defines aliases for the patch class. Sometimes, When you want to change the class name then it could possible using getAliases() function. If it does, then we should add old class name so, it’s not executed a second time.

In Last, getVersion() function will return a version of the patch. If the version of the module will be high than the version we specify in our patch, then it will not get executed. It will executed only when it’s equal to or lower than the version here.

2) In Last, Now just execute this below command :

php bin/magento s:up
php bin/magento s:s:d -f
php bin/magento c:c

That’s it !!

Now, you can see in eav_attribute table that your custom product attribute created successfully using data patch.

I hope this blog is easy to understand about how to create a product attribute using data patches in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Keep liking and sharing !!

Tagged ,