Magento 2 is a widely used platform by various types of businesses. Hence, the checkout page, shipping or billing page may not be the same as the default Magento 2 for every store. According to the business requirement, the address forms may vary.
For example, implementing the Indian GST tax in Magento 2 store requires to add Buyer GST number field in the checkout form. It is a custom field that needs to be programmatically added to get buyer GSTIN from the customers. Here. I’ll show how to add custom field in address form in Magento 2.
Method to Add Custom Field in Address Form in Magento 2:
1. Create registration.php file in app\code\[Vendor]\[Namespace]\
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, '[Vendor]_[Namespace]', __DIR__ );
2. Create module.xml file in app\code\[Vendor]\[Namespace]\etc
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="[Vendor]_[Namespace]" setup_version="1.0.0"/> </config>
3. Create di.xml file in app\code\[Vendor]\[Namespace]\etc
<?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\Checkout\Block\Checkout\LayoutProcessor"> <plugin name="gst_number" type="[Vendor]\[Namespace]\Plugin\Checkout\Model\LayoutProcessor" sortOrder="100"/> </type> </config>
4. Create LayoutProcessor.php in [Vendor]\[Namespace]\Plugin\Checkout\Model
<?php namespace Vendor\Extension\Plugin\Checkout\Model; use Magento\Checkout\Block\Checkout\LayoutProcessor as ChekcoutLayerprocessor; class LayoutProcessor { protected $dataHelper; public function __construct(\Vendor\Extension\Helper\Data $dataHelper) { $this->dataHelper = $dataHelper; } public function afterProcess(ChekcoutLayerprocessor $subject, array $jsLayout) { $flag = false; if ($this->dataHelper->getBuyerGst()) { $flag = true; } $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children'] ['shippingAddress']['children']['shipping-address-fieldset']['children']['buyer_gst_number'] = [ 'component' => 'Magento_Ui/js/form/element/abstract', 'config' => [ 'customScope' => 'shippingAddress', 'template' => 'ui/form/field', 'elementTmpl' => 'ui/form/element/input', 'options' => [], 'id' => 'gst_number' ], 'dataScope' => 'shippingAddress.buyer_gst_number', 'label' => 'GST Number#', 'provider' => 'checkoutProvider', 'visible' => $flag, 'validation' => [], 'sortOrder' => 252, 'id' => 'buyer_gst_number' ]; return $jsLayout; } }
With the above method, you can add as many custom fields you want in the address form in Magento 2.
Thanks!