Friday, 8 November 2019

Add customer attribute programmatically in Magento 2.3 using Data Patch

1.Create file registration.php in app/code/Custom/CustomerAttribute/registration.php

<?php
/**
 * Ansar Husain
 * Custom_CustomerAttribute
 */
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Custom_CustomerAttribute,
    __DIR__
);



2. Create file module.xml app/code/Custom/CustomerAttribute/etc/module.xml

<?xml version="1.0"?>
<!--
/**
* Ansar Husain
* Custom_CustomerAttribute
**/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Custom_CustomerAttribute" />
</config>

3. Create file AddCustomCustomerAttribute.php app/code/Custom/CustomerAttribute/Setup/Patch/Data/AddCustomCustomerAttribute.php


<?php
namespace Custom\CustomerAttribute\Setup\Patch\Data;
use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Setup\Patch\Data\UpdateIdentifierCustomerAttributesVisibility;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class AddCustomCustomerAttribute implements DataPatchInterface{

    protected $_moduleDataSetup;

    protected $_customerSetupFactory;

    public function __construct(ModuleDataSetupInterface $moduleDataSetup, CustomerSetupFactory $customerSetupFactory)
    {
        $this->_moduleDataSetup = $moduleDataSetup;
        $this->_customerSetupFactory = $customerSetupFactory;

    }

    public static function getDependencies()
    {
        return [
            UpdateIdentifierCustomerAttributesVisibility::class,
        ];
        // TODO: Implement getDependencies() method.
    }

    public function getAliases()
    {
        return [];
        // TODO: Implement getAliases() method.
    }
    public function apply()
    {
        $customerSetup = $this->_customerSetupFactory->create(['setup'=>$this->_moduleDataSetup]);

        $customerSetup->addAttribute(Customer::ENTITY,'customer_custom_attribute',
            [
               'type' => 'int',
               'label' => 'Customer Custom Attribute',
               'input' => 'text',
               'required' => false,
               'sort_order' => 150,
               'system' => false,
               'visible' => true
            ]);


        // TODO: Implement apply() method.
    }
    public function getVersion(){

        return '2.0.0';
    }

}


No comments:

Post a Comment