Friday, 8 November 2019

Add customer address attribute programmatically in Magento 2.3 using Data Patch

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

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



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

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

3. Create file AddCustomerCustomAddressAttribute.php app/code/Custom/CustomerAddressAttribute/Setup/Patch/Data/AddCustomerCustomAddressAttribute.php

<?php

namespace Custom\CustomerAddressAttribute\Setup\Patch\Data;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Setup\Patch\Data\UpdateVATNumber;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\PatchVersionInterface;

class AddCustomerCustomAddressAttribute implements DataPatchInterface ,PatchVersionInterface
{
    protected $_moduleDataSetup;

    protected $_customerSetupFactory;

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

    public function apply()
    {
        $customerSetup = $this->_customerSetupFactory->create(['setup'=>$this->_moduleDataSetup]);

        $customerSetup->addAttribute('customer_address','custom_address_attribute',[
           'type' => 'text',
           'input' => 'textarea',
            'label' => 'Custom Address Attribute',
            'visible' => true,
            'user_defined'=> true,
            'system' => false

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

        // TODO: Implement getDependencies() method.
    }

    public function getAliases()
    {
        return [];
        // TODO: Implement getAliases() method.
    }

    public static function getVersion()
    {
        return '2.5.5';
        // TODO: Implement getVersion() method.
    }

}


No comments:

Post a Comment