Magento2: How to Add Customer Address Attribute Using Data Patch

Add Customer Address Attribute Using Data patch in Magento 2

Let’s see how we can add customer address attributes programmatically using the data patch in this post. We have seen how we can add product attributes programmatically using the data patch in a the post https://sbdevblog.com/magento-2-add-product-attribute-using-data-patch/.

Very often we need to collect extra information from customer related from shipping / billing address. In such case, we have to create EAV attribute with type customer_address.

Let’s implement it practically. I assume you already have created a basic module structure with a suitable vendor name.

Add Customer Address Attribute Using Data Patch In Magento 2

In my Case, Vendor Name is SbDevBlog. I have created data patch file inside module SbDevBlog/Customer.

So, We need to create the data patch file inside Vendor/Module/Setup/Patch/Data directory.

I have created the data patch file as given below.

<?php
/**
 * @copyright Copyright (c) sbdevblog https://www.sbdevblog.com)
 */

declare(strict_types=1);

namespace SbDevBlog\Customer\Setup\Patch\Data;

use Magento\Customer\Setup\CustomerSetup;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\Patch\PatchVersionInterface;
use Psr\Log\LoggerInterface;

/**
 * Class extra information customer address attribute create
 */
class AddExtraInfoCustomerAddressAttributePatch implements DataPatchInterface, PatchVersionInterface
{
    /**
     * @var CustomerSetupFactory
     */
    private CustomerSetupFactory $customerSetupFactory;

    /**
     * @var ModuleDataSetupInterface
     */
    private ModuleDataSetupInterface $moduleDataSetup;

    /**
     * @var LoggerInterface
     */
    private LoggerInterface $logger;

    /**
     * Constructor
     *
     * @param CustomerSetupFactory $customerSetupFactory
     * @param ModuleDataSetupInterface $moduleDataSetup
     * @param LoggerInterface $logger
     */
    public function __construct(
        CustomerSetupFactory $customerSetupFactory,
        ModuleDataSetupInterface $moduleDataSetup,
        LoggerInterface $logger
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
        $this->moduleDataSetup = $moduleDataSetup;
        $this->logger = $logger;
    }

    /**
     * @inheritdoc
     *
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function apply()
    {
        /** @var CustomerSetup $customerSetup */
        $customerSetup = $this->customerSetupFactory->create(['setup' => $this->moduleDataSetup]);

        $attributesInfo = [
            'extra_info_demo' => [
                'label' => 'Extra Information For Demo Address',
                'type'             => 'varchar',
                'input'            => 'text',
                'visible'          => true,
                'required'         => false,
                'user_defined'     => true,
                'system'           => false,
                'group'            => 'General',
                'global'           => true,
                'visible_on_front' => false,
            ],
            //You may add your new attributes in array
        ];

        foreach ($attributesInfo as $attributeCode => $attributeParams) {
            try {
                $customerSetup->addAttribute('customer_address', $attributeCode, $attributeParams);
                $extraInfoAttribute = $customerSetup->getEavConfig()->getAttribute('customer_address', $attributeCode);

                $extraInfoAttribute->setData(
                    'used_in_forms',
                    ['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address']
                );
                $extraInfoAttribute->save();
            } catch (LocalizedException|\Zend_Validate_Exception|\Exception $e) {
                $this->logger->error($e->getMessage());
            }
        }

        return $this;
    }

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

    /**
     * @inheritdoc
     */
    public static function getVersion()
    {
        return '2.0.0';
    }

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

That’s it. It will create an attribute with name extra_info_demo. You may replace with your attribute data or append new attribute’s data in array.

Code given below is responsible to make our attributes visible and editable inside our forms. so keep it as per your requirement.

$extraInfoAttribute->setData(
                    'used_in_forms',
                    ['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address']

Thanks for reading my blog Add Customer Address Attribute Using Data Patch In Magento 2

You may Download Source Code.

Note: Please verify the code of this blog and the relevant git repository before using it in production.
sb dev blog adobe commece Magento 2

🙂 HAPPY CODING 🙂

One thought on “Magento2: How to Add Customer Address Attribute Using Data Patch

Leave a Reply

Your email address will not be published. Required fields are marked *