Reading list Switch to dark mode

    How to create customer address field in Magento 2

    Updated 13 December 2023

    Sometimes we need to get more information of the customer such as GST number, alternate mobile number etc. We can get the extra information of the customer.

    Here we will follow the webkul sample module Magento 2 hello world extension

    1. We need to create customer address attribute with the help of patch at app/code/Webkul/Hello/Setup/Patch/Data/GstAttribute.php
    <?php
    namespace Webkul\Hello\Setup\Patch\Data;
    
    use Magento\Framework\Setup\Patch\DataPatchInterface;
    use Magento\Framework\Setup\ModuleDataSetupInterface;
    use Magento\Eav\Setup\EavSetupFactory;
    use Magento\Catalog\Model\Product;
    use Magento\Customer\Api\AddressMetadataInterface;
    use Magento\Eav\Model\Config as EavConfig;
    use Magento\Catalog\Model\Product\Attribute\Backend\Price;
    use Magento\Customer\Setup\CustomerSetupFactory;
    use Magento\Customer\Model\Customer;
    use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
    
    class GstAttribute implements DataPatchInterface
    {
        /**
         * GSTIN Attribute Code
         */
        public const GSTIN_CODE = 'wkgstin';
    
        /**
         * @var EavSetupFactory
         */
        private $eavSetupFactory;
    
        /**
         * @var ModuleDataSetupInterface
         */
        private $moduleDataSetup;
    
        /**
         * EAV Config data.
         *
         * @var EavConfig
         */
        private $eavConfig;
    
        /**
         * @var CustomerSetupFactory
         */
        protected $customerSetupFactory;
    
        /**
         * @var AttributeSetFactory
         */
        private $attributeSetFactory;
    
        /**
         * Constructor Initialize
         *
         * @param EavSetupFactory $eavSetupFactory
         * @param EavConfig $eavConfig
         * @param CustomerSetupFactory $customerSetupFactory
         * @param ModuleDataSetupInterface $moduleDataSetup
         * @param AttributeSetFactory $attributeSetFactory
         * @return void
         */
        public function __construct(
            EavSetupFactory $eavSetupFactory,
            EavConfig $eavConfig,
            CustomerSetupFactory $customerSetupFactory,
            ModuleDataSetupInterface $moduleDataSetup,
            AttributeSetFactory $attributeSetFactory
        ) {
            $this->eavConfig = $eavConfig;
            $this->eavSetupFactory = $eavSetupFactory;
            $this->customerSetupFactory = $customerSetupFactory;
            $this->moduleDataSetup = $moduleDataSetup;
            $this->attributeSetFactory = $attributeSetFactory;
        }
    
        /**
         * Do Upgrade
         *
         * @return void
         */
        public function apply()
        {
            $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
    
            /* Create GSTIN Attribute */
            $eavSetup->addAttribute(
                AddressMetadataInterface::ENTITY_TYPE_ADDRESS,
                self::GSTIN_CODE,
                [
                    'label' => 'GST No',
                    'input' => 'text',
                    'visible' => true,
                    'required' => false,
                    'position' => 200,
                    'sort_order' => 200,
                    'system' => false
                ]
            );
    
            $gstAttribute = $this->eavConfig->getAttribute(
                AddressMetadataInterface::ENTITY_TYPE_ADDRESS,
                self::GSTIN_CODE
            );
    
            $gstAttribute->setData(
                'used_in_forms',
                ['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address']
            );
            $gstAttribute->save();
        }
        /**
         * Get aliases
         *
         * @return void
         */
        public function getAliases()
        {
            return [];
        }
    
        /**
         * Get dependencies
         *
         * @return void
         */
        public static function getDependencies()
        {
            return [];
        }
    }

    2) Now we need to register a plugin for adding field in customer address form at customer end.
    app/code/Webkul/Hello/etc/di.xml

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
        <type name="Magento\Customer\Block\Address\Edit">
            <plugin name="wkgst_address_gstin" type="Webkul\Hello\Plugin\Customer\AddressEdit" sortOrder="2"/>
        </type>
    <type name="Magento\Checkout\Model\ShippingInformationManagement">
            <plugin name="save_to_quote_table" type="Webkul\Hello\Plugin\Checkout\Model\ShippingInformationManagement" sortOrder="1" />
        </type>
    </config>

    app/code/Webkul/Hello/extension_attributes.xml

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
        <extension_attributes for="Magento\Quote\Api\Data\AddressInterface">
            <attribute code="wkgstin" type="string" />
        </extension_attributes>
    </config>

    app/code/Webkul/Hello/Plugin/Checkout/Model/ShippingInformationManagement.php

    Start your headless eCommerce
    now.
    Find out More
    <?php
    namespace Webkul\Hello\Plugin\Checkout\Model;
    
    use Magento\Quote\Model\QuoteRepository;
    use \Psr\Log\LoggerInterface;
    
    class ShippingInformationManagement{
        
        protected $quoteRepository;
        protected $logger;
    
        public function __construct(QuoteRepository $quoteRepository,  LoggerInterface $logger) {
            $this->quoteRepository = $quoteRepository;
            $this->logger = $logger;
        }
    
        public function beforeSaveAddressInformation(
            \Magento\Checkout\Model\ShippingInformationManagement $subject,
            $cartId,
            \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
        ) {
            $shippingAddress = $addressInformation->getShippingAddress();
            $extensionAttributes = $shippingAddress->getExtensionAttributes();
    
            if ($extensionAttributes) {
                if ($extensionAttributes->getWkgstin()) {
                    $gstin = $extensionAttributes->getWkgstin();
                    $shippingAddress->setWkgstin($gstin);
                } else {
                    $shippingAddress->setWkgstin('');
                }
            }
        }
    }

    3) app/code/Webkul/Hello/Plugin/Customer/AddressEdit.php

    <?php
    namespace Webkul\Hello\Plugin\Customer;
    
    use Magento\Framework\View\LayoutInterface;
    use Webkul\Hello\Block\Customer\AddressEdit as CustomerAddress;
    
    class AddressEdit
    {
        /**
         * @var LayoutInterface
         */
        private $layout;
    
        /**
         * Constructor Initialize
         *
         * @param LayoutInterface $layout
         * @return void
         */
        public function __construct(
            LayoutInterface $layout
        ) {
            $this->layout = $layout;
        }
    
        /**
         * Append gst field
         *
         * @param \Magento\Customer\Block\Address\Edit $edit
         * @param string $result
         * @return mixed|string
         */
        public function afterGetNameBlockHtml(
            \Magento\Customer\Block\Address\Edit $edit,
            $result
        ) {
            $customBlock =  $this->layout->createBlock(
                CustomerAddress::class,
                'wkgst_address_edit_gstin'
            );
            
            return $result.$customBlock->toHtml();
        }
    }

    4) app/code/Webkul/Hello/Block/Customer/AddressEdit.php

    <?php
    namespace Webkul\Hello\Block\Customer;
    
    use Magento\Framework\View\Element\Template;
    use Webkul\Hello\Block\Customer\Widget\Gstin;
    
    class AddressEdit extends Template
    {
        /**
         * To html
         *
         * @return string
         */
        protected function _toHtml()
        {
            $gstinWidgetBlock = $this->getLayout()->createBlock(Gstin::class);
            return $gstinWidgetBlock->toHtml();
        }
    }

    5) app/code/Webkul/Hello/Block/Customer/Widget/Gstin.php

    <?php
    namespace Webkul\Hello\Block\Customer\Widget;
    
    use Magento\Customer\Model\AddressFactory;
    use Magento\Framework\View\Element\Template;
    use Magento\Framework\View\Element\Template\Context;
    
    class Gstin extends Template
    {
        /**
         * @var AddressFactory
         */
        protected $_addressFactory;
    
        /**
         * Constructor Initialize
         *
         * @param Context $context
         * @param AddressFactory $addressFactory
         * @param array $data
         * @return void
         */
        public function __construct(
            Context $context,
            AddressFactory $addressFactory,
            array $data = []
        ) {
            $this->_addressFactory = $addressFactory;
            parent::__construct($context, $data);
        }
    
        /**
         * Set custom template
         *
         * @return void
         */
        public function _construct()
        {
            parent::_construct();
    
            // default template location
            $this->setTemplate('Webkul_Hello::widget/gstno.phtml');
        }
    
        /**
         * Return gstin number from address
         *
         * @return string|null
         */
        public function getValue()
        {
            $addressId = $this->getRequest()->getParam('id');
            if ($addressId) {
                $addressCollection = $this->_addressFactory->create()->load($addressId);
                $gstin = $addressCollection->getWkgstin();
                if ($gstin) {
                    return $gstin;
                }
            }
            return null;
        }
    }

    6) app/code/Webkul/Hello/view/frontend/templates/widget/gstno.phtml

    <?php
    /**
     * @var \Webkul\Module\Block\Customer\Widget\Gstin $block
     */
    ?>
    <div class="field field-name-gstno">
        <label class="label" for="<?= $block->escapeHtml('wkgstin') ?>">
            <span><?= $block->escapeHtml(__('GST No.')) ?></span>
        </label>
        <div class="control">
            <input type="text"
                id="<?= $block->escapeHtml('wkgstin') ?>"
                name="<?= $block->escapeHtml('wkgstin') ?>"
                value="<?= $block->escapeHtml($block->getValue()) ?>"
                title="<?= $block->escapeHtml(__('GST No')) ?>"
                class="input-text"
            >
        </div>
    </div>

    7) Execute following commands in magento root directory

    php bin/magento setup:upgrade
    php bin/magento setup:di:compile
    php bin/magento setup:static-content:deploy -f

    That is all for this blog, you may also check our best Magento 2 extensions

    . . .

    Leave a Comment

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


    6 comments

  • Geo
    • Amir Khan (Moderator)
  • rahul rai
    • Ritika Singh (Moderator)
  • rahul rai
    • Amir Khan (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home