Magento2 | PWA | GraphQL

Add Custom Checkout field GST Number in Shipping Address information form in Magento2


In this post we wiil check how to add custom checkout field (GST Number) in Shipping Address information form in Magento2.

We will check how to add custom field with UI Component LayoutProcessor method and add extension_attributes in ShippingInformationManagement.

Let's start by creating custom module.

You can find complete module on Github at Magelearn_GstCheckout





Create folder inside app/code/Magelearn/GstCheckout

Add registration.php file in it:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magelearn_GstCheckout',
    __DIR__
);
Add composer.json file in it:
{
    "name": "magelearn/gst-checkout",
    "description": "Add custom field - GST Number on Checkout Page for Magento 2",
    "type": "magento2-module",
    "license": "proprietary",
    "authors": [
        {
            "name": "vijay rami",
            "email": "vijaymrami@gmail.com"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "files": [ "registration.php" ],
        "psr-4": {
            "Magelearn\\GstCheckout\\": ""
        }
    }
}
Add etc/module.xml file in it:
<?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="Magelearn_GstCheckout" setup_version="2.0.2" />
</config>
Now, we will add database setup script.
Create db_schema.xml file in etc folder.
this script will add new column `gst_number` in `sales_order` and `quote` table.
<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    <table name="sales_order" resource="sales" engine="innodb" comment="Gst Number">
        <column xsi:type="text" name="gst_number" nullable="false"  comment="Gst Number"/>
    </table>
    <table name="quote" resource="checkout" engine="innodb" comment="Gst Number">
        <column xsi:type="text" name="gst_number" nullable="false"  comment="Gst Number"/>
    </table>
</schema>

To validate this db_schema.xml file we will first run below command:

php bin/magento setup:db-declaration:generate-whitelist --module-name=Magelearn_GstCheckout

This command will automatically generate db_schema_whitelist.json file inside etc folder.

First we will provide some default configurations for this new field.

Add app/code/Magelearn/ShippingNotes/etc/adminhtml/system.xml file.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="gstnumber" translate="label" sortOrder="10">
            <label>Magelearn</label>
        </tab>
        <section id="gstnumber" translate="label" sortOrder="130" showInDefault="1" showInWebsite="1" showInStore="1">
            <class>separator-top</class>
            <label>GST Number Configuration</label>
            <tab>gstnumber</tab>
            <resource>Magelearn_GstCheckout::gstnumber_config</resource>
            <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>General Configuration</label>
                <field id="enable" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Enable</label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                </field>
            </group>
        </section>
    </system>
</config>

Add app/code/Magelearn/ShippingNotes/etc/config.xml file.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <gstnumber>
            <general>
            	<enable>1</enable>
            </general>
        </gstnumber>
    </default>
</config>

We will add this new field on shipping information form by adding UI Component in Magento\Checkout\Block\Checkout\LayoutProcessor

First add app/code/Magelearn/GstCheckout/etc/di.xml file.

<?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\Model\ShippingInformationManagement">
        <plugin name="magelearn_save_gst_number_in_quote" type="Magelearn\GstCheckout\Plugin\Checkout\Model\ShippingInformationManagement" sortOrder="1"/>
    </type>
    <type name="Magento\Checkout\Block\Checkout\LayoutProcessor">
        <plugin name="magelearn_checkout_layout_processor_add_gst_number_block"
                type="Magelearn\GstCheckout\Plugin\Checkout\Block\LayoutProcessor" sortOrder="1"/>
    </type>
</config>

Here in Plugin method for Magento\Checkout\Block\Checkout\LayoutProcessor we will add our custom field UI component in afterProcess method.

And in Plugin method for Magento\Checkout\Model\ShippingInformationManagement we will add our extension attributes (gst_number) in Quote object inside beforeSaveAddressInformation method.

Add app/code/Magelearn/GstCheckout/Plugin/Checkout/Block/LayoutProcessor.php file.

<?php
namespace Magelearn\GstCheckout\Plugin\Checkout\Block;

use Magelearn\GstCheckout\Model\Config;

class LayoutProcessor
{
    /**
     * @var \Magelearn\GstCheckout\Model\Config
     */
    protected $config;

    /**
     * LayoutProcessor constructor.
     *
     * @param Config $config
     */
    public function __construct(
        Config $config
    ) {
        $this->config = $config;
    }

    /**
     * @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
     * @param array $jsLayout
     * @return array
     */
    public function afterProcess(
        \Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
        array $jsLayout
    ) {
        $status =  $this->config->getstatus();
        if($status == 1){
            $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']
            ['children']['shippingAddress']['children']['shipping-address-fieldset']['children']['gst_number'] = [
                'component' => 'uiComponent',
                //'displayArea' => 'shippingAdditional',
                'children' => [
                    'gst_number' => [
                        'component' => 'Magento_Ui/js/form/element/abstract',
                        'config' => [
                            'customScope' => 'gst_number',
                            'template' => 'ui/form/field',
                            'elementTmpl' => 'ui/form/element/input',
                            'options' => [],
                            'id' => 'gst_number'
                        ],
                        'dataScope' => 'gst_number.gst_number',
                        'label' => 'GST Number :',
                        'provider' => 'checkoutProvider',
                        'visible' => true,
                        'validation' => [],
                        'sortOrder' => 20,
                        'id' => 'gst_number'
                    ]
                ]
            ];
        }
        return $jsLayout;
    }
}

Add app/code/Magelearn/GstCheckout/Plugin/Checkout/Model/ShippingInformationManagement.php file.

<?php
namespace Magelearn\GstCheckout\Plugin\Checkout\Model;

use Magento\Quote\Model\QuoteRepository;
use Magento\Checkout\Api\Data\ShippingInformationInterface;

class ShippingInformationManagement
{
    /**
     * @var QuoteRepository
     */
    protected $quoteRepository;

    /**
     * ShippingInformationManagement constructor.
     *
     * @param QuoteRepository $quoteRepository
     */
    public function __construct(
        QuoteRepository $quoteRepository
    ) {
        $this->quoteRepository = $quoteRepository;
    }

    /**
     * @param \Magento\Checkout\Model\ShippingInformationManagement $subject
     * @param $cartId
     * @param ShippingInformationInterface $addressInformation
     */
    public function beforeSaveAddressInformation(
        \Magento\Checkout\Model\ShippingInformationManagement $subject,
        $cartId,
        ShippingInformationInterface $addressInformation
    ) {
        $extAttributes = $addressInformation->getExtensionAttributes();
        $gstNumber = $extAttributes->getGstNumber();
        $quote = $this->quoteRepository->getActive($cartId);
        $quote->setGstNumber($gstNumber);
    }
}

We will add app/code/Magelearn/GstCheckout/Model/Config.php file to check for the configuration is set to yes or no.

<?php
namespace Magelearn\GstCheckout\Model;

use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Framework\App\State as AppState;
use Magento\Sales\Model\AdminOrder\Create as AdminOrderCreate;

class Config
{
    const XPATH_STATUS  = 'gstnumber/general/enable';

    /**
     * @var int
     */
    protected $storeId;

    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var AppState
     */
    protected $appState;

    /**
     * @var AdminOrderCreate
     */
    protected $adminOrderCreate;

    /**
     * Config constructor.
     *
     * @param StoreManagerInterface $storeManager
     * @param ScopeConfigInterface $scopeConfig
     * @param AppState $appState
     * @param AdminOrderCreate $adminOrderCreate
     */
    public function __construct(
        StoreManagerInterface $storeManager,
        ScopeConfigInterface $scopeConfig,
        AppState $appState,
        AdminOrderCreate $adminOrderCreate
    ) {
        $this->storeManager = $storeManager;
        $this->scopeConfig = $scopeConfig;
        $this->appState = $appState;
        $this->adminOrderCreate = $adminOrderCreate;
    }
    /**
     * @return int
     */
    public function getStoreId()
    {
        if (!$this->storeId) {
            if ($this->appState->getAreaCode() == 'adminhtml') {
                $this->storeId = $this->adminOrderCreate->getQuote()->getStoreId();
            } else {
                $this->storeId = $this->storeManager->getStore()->getStoreId();
            }
        }

        return $this->storeId;
    }
    /**
     * @return mixed
     */
    public function getstatus()
    {
        $store = $this->getStoreId();
        return $this->scopeConfig->getValue(self::XPATH_STATUS, ScopeInterface::SCOPE_STORE, $store);
    }
}

Now we will add app/code/Magelearn/GstCheckout/etc/extension_attributes.xml file to add `gst_number`  as extension_attributes for ShippingInformationManagement

<?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\Checkout\Api\Data\ShippingInformationInterface">
        <attribute code="gst_number" type="string"/>
    </extension_attributes>
</config>

Add app/code/Magelearn/GstCheckout/etc/fieldset.xml file.

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:DataObject/etc/fieldset.xsd">
    <scope id="global">
        <fieldset id="sales_convert_quote">
            <field name="gst_number">
                <aspect name="to_order"/>
            </field>
        </fieldset>
    </scope>
</config>

Now we will add app/code/Magelearn/GstCheckout/etc/events.xml file to save Quote data into order data.

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_model_service_quote_submit_before">
        <observer name="magelearn_gst_number" instance="Magelearn\GstCheckout\Observer\SalesModelServiceQuoteSubmitBefore"/>
    </event>
</config>

Add app/code/Magelearn/GstCheckout/Observer/SalesModelServiceQuoteSubmitBefore.php file.

<?php
namespace Magelearn\GstCheckout\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Quote\Model\QuoteRepository;

class SalesModelServiceQuoteSubmitBefore implements ObserverInterface
{
	/**
     * @var \Magento\Framework\DataObject\Copy
     */
    protected $objectCopyService;
    /**
     * @var QuoteRepository
     */
    private $quoteRepository;
	
    /**
     * SalesModelServiceQuoteSubmitBefore constructor.
     *
     * @param QuoteRepository $quoteRepository
     * @param Validator $validator
     */
     /**
     * @param \Magento\Framework\DataObject\Copy $objectCopyService
     */
    public function __construct(
        QuoteRepository $quoteRepository,
        \Magento\Framework\DataObject\Copy $objectCopyService
    ) {
        $this->quoteRepository = $quoteRepository;
		$this->objectCopyService = $objectCopyService;
    }

    /**
     * @param EventObserver $observer
     * @return $this
     * @throws \Exception
     */
    public function execute(EventObserver $observer)
    {
		/** @var \Magento\Sales\Model\Order $order */
        $order = $observer->getEvent()->getData('order');
        /** @var \Magento\Quote\Model\Quote $quote */
        $quote = $observer->getEvent()->getData('quote');
		
		$order->setGstNumber($quote->getGstNumber());
        
		$this->objectCopyService->copyFieldsetToTarget('sales_convert_quote', 'to_order', $quote, $order);

        return $this;
    }
}

Now to save this checkout field properly into database, we will pass this field value into payload >> addressInformation >> extension_attributes array.

For that we have to override Magento_Checkout/js/model/shipping-save-processor/default.js file.

Add app/code/Magelearn/GstCheckout/view/frontend/requirejs-config.js file.

var config = {
    "map": {
        "*": {
            'Magento_Checkout/js/model/shipping-save-processor/default': 'Magelearn_GstCheckout/js/model/shipping-save-processor/default'
        }
    }
};

Now add app/code/Magelearn/GstCheckout/view/frontend/web/js/model/shipping-save-processor/default.js file.

/*global define,alert*/
define(
    [
        'jquery',
        'ko',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/model/resource-url-manager',
        'mage/storage',
        'Magento_Checkout/js/model/payment-service',
        'Magento_Checkout/js/model/payment/method-converter',
        'Magento_Checkout/js/model/error-processor',
        'Magento_Checkout/js/model/full-screen-loader',
        'Magento_Checkout/js/action/select-billing-address'
    ],
    function (
        $,
        ko,
        quote,
        resourceUrlManager,
        storage,
        paymentService,
        methodConverter,
        errorProcessor,
        fullScreenLoader,
        selectBillingAddressAction
    ) {
        'use strict';

        return {
            saveShippingInformation: function () {
                var payload;

                if (!quote.billingAddress()) {
                    selectBillingAddressAction(quote.shippingAddress());
                }

                payload = {
                    addressInformation: {
                        shipping_address: quote.shippingAddress(),
                        billing_address: quote.billingAddress(),
                        shipping_method_code: quote.shippingMethod().method_code,
                        shipping_carrier_code: quote.shippingMethod().carrier_code,
                        extension_attributes:{
                            gst_number: $('[name="gst_number"]').val()
                        }
                    }
                };

                fullScreenLoader.startLoader();

                return storage.post(
                    resourceUrlManager.getUrlForSetShippingInformation(quote),
                    JSON.stringify(payload)
                ).done(
                    function (response) {
                        quote.setTotals(response.totals);
                        paymentService.setPaymentMethods(methodConverter(response.payment_methods));
                        fullScreenLoader.stopLoader();
                    }
                ).fail(
                    function (response) {
                        errorProcessor.process(response);
                        fullScreenLoader.stopLoader();
                    }
                );
            }
        };
    }
);

Now we will check how to display this extra field in Admin.
To do that we will add some events for admin in events.xml file.

Add app/code/Magelearn/GstCheckout/etc/adminhtml/events.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="core_layout_render_element">
        <observer name="magelearn_gst_number_add_to_order_view"
                  instance="Magelearn\GstCheckout\Observer\AddHtmlToOrderShippingView" />
    </event>
    <event name="adminhtml_sales_order_create_process_data">
        <observer name="magelearn_gst_number_adminhtml_sales_order_create_process_data"
                  instance="Magelearn\GstCheckout\Observer\AdminhtmlSalesOrderCreateProcessData"/>
    </event>
</config>

Here core_layout_render_element event is used to display this field information on admin order view page.

And adminhtml_sales_order_create_process_data event is used to add this new field into the quote object when create order from admin.

Now, create app/code/Magelearn/GstCheckout/Observer/AddHtmlToOrderShippingView.php file.

<?php
namespace Magelearn\GstCheckout\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\View\Element\TemplateFactory;
use Magento\Store\Model\ScopeInterface;

class AddHtmlToOrderShippingView implements ObserverInterface
{
    /**
     * @var TemplateFactory
     */
    protected $templateFactory;

    /**
     * AddHtmlToOrderShippingBlock constructor.
     *
     * @param TemplateFactory $templateFactory
     * @param TimezoneInterface $timezone
     */
    public function __construct(
        TemplateFactory $templateFactory
    ) {
        $this->templateFactory = $templateFactory;
    }

    /**
     * @param EventObserver $observer
     * @return $this
     */
    public function execute(EventObserver $observer)
    {
        if($observer->getElementName() == 'order_shipping_view') {
            $orderShippingViewBlock = $observer->getLayout()->getBlock($observer->getElementName());
            $order = $orderShippingViewBlock->getOrder();

            /** @var \Magento\Framework\View\Element\Template $gstNumberBlock */
            $gstNumberBlock = $this->templateFactory->create();
            $gstNumberBlock->setGstNumber($order->getGstNumber());
            $gstNumberBlock->setTemplate('Magelearn_GstCheckout::order_info_shipping_info.phtml');
            $html = $observer->getTransport()->getOutput() . $gstNumberBlock->toHtml();
            $observer->getTransport()->setOutput($html);
        }

        return $this;
    }
}

Now add app/code/Magelearn/GstCheckout/view/adminhtml/templates/order_info_shipping_info.phtml file.

<section class="admin__page-section" id="gst-number-content">
    <div class="admin__page-section-title">
        <span class="title"><?= $block->escapeHtml(__('GST Information')) ?></span>
    </div>
    <div class="admin__page-section-content">
        
        <div id="gst-number">
            <strong><?= __('GST Number') ?>:</strong>
            <?= $block->getGstNumber() ?>
        </div>
    </div>
</section>
<script type="text/javascript">
    require(
        ['jquery'],
        function($) {
            $('#gst-number-content').insertAfter($('.order-view-billing-shipping'));
        }
    );
</script>

Now, we will add observer for adminhtml_sales_order_create_process_data

Add app/code/Magelearn/GstCheckout/Observer/AdminhtmlSalesOrderCreateProcessData.php file.

<?php
namespace Magelearn\GstCheckout\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;

class AdminhtmlSalesOrderCreateProcessData implements ObserverInterface
{
    /**
     * @param EventObserver $observer
     * @return $this
     */
    public function execute(EventObserver $observer)
    {
        $requestData = $observer->getRequest();
        $gst_number = isset($requestData['gst_number']) ? $requestData['gst_number'] : null;

        /** @var \Magento\Sales\Model\AdminOrder\Create $orderCreateModel */
        $orderCreateModel = $observer->getOrderCreateModel();
        $quote = $orderCreateModel->getQuote();
        $quote->setGstNumber($gst_number);

        return $this;
    }
}

Now, we will add layout file for creating orders from admin.

Create app/code/Magelearn/GstCheckout/view/adminhtml/layout/sales_order_create_index.xml file.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="shipping_method">
            <block class="Magelearn\GstCheckout\Block\Adminhtml\GstNumber"
                   template="Magelearn_GstCheckout::order/create/gst_number.phtml"
                   name="gst_number" as="gst_number" after="-"/>
        </referenceBlock>
    </body>
</page>

Create app/code/Magelearn/GstCheckout/view/adminhtml/layout/sales_order_create_load_block_shipping_method.xml file.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="shipping_method">
            <block class="Magelearn\GstCheckout\Block\Adminhtml\GstNumber"
                   template="Magelearn_GstCheckout::order/create/gst_number.phtml"
                   name="gst_number" as="gst_number" after="-"/>
        </referenceBlock>
    </body>
</page>

Add app/code/Magelearn/GstCheckout/view/adminhtml/templates/order/create/gst_number.phtml file.

<?php /** @var \Magelearn\GstCheckout\Block\Adminhtml\GSTNumber $block */ ?>
<?php if($block->getConfig()):?>
<div class="admin__field field-comment">
    <label for="gst_number" class="admin__field-label"><span><?= __('GST Number') ?></span></label>
    <div class="admin__field-control">
        <input
                id="gst_number"
                name="gst_number"
                class="admin__control-input" >
    </div>
</div>
<?php endif; ?>

Now we will also create our block file.
Add app/code/Magelearn/GstCheckout/Block/Adminhtml/GstNumber.php file.

<?php
namespace Magelearn\GstCheckout\Block\Adminhtml;

use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magelearn\GstCheckout\Model\Config;

class GstNumber extends Template
{
    /**
     * @var Config
     */
    private $config;

    /**
     * GST Number constructor.
     *
     * @param Context $context
     * @param Config $config
     * @param array $data
     */
    public function __construct(
        Context $context,
        Config $config,
        array $data = []
    ) {
    	$this->config = $config;
        parent::__construct($context, $data);
    }

    /**
     * @return string
     */
    public function getConfig()
    {
        return $this->config->getstatus();
    }

}

Now we will check how to addd this new field information on front end.

Create app/code/Magelearn/GstCheckout/etc/frontend/events.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="core_layout_render_element">
        <observer name="magelearn_gst_number_add_to_order_view" instance="Magelearn\GstCheckout\Observer\AddHtmlToOrderShippingBlock" />
    </event>
</config>

Add observer file app/code/Magelearn/GstCheckout/Observer/AddHtmlToOrderShippingBlock.php

<?php
namespace Magelearn\GstCheckout\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\View\Element\TemplateFactory;
use Magento\Store\Model\ScopeInterface;

class AddHtmlToOrderShippingBlock implements ObserverInterface
{
    /**
     * @var TemplateFactory
     */
    protected $templateFactory;

    /**
     * AddHtmlToOrderShippingBlock constructor.
     *
     * @param TemplateFactory $templateFactory
     * @param TimezoneInterface $timezone
     */
    public function __construct(
        TemplateFactory $templateFactory
    ) {
        $this->templateFactory = $templateFactory;
    }

    /**
     * @param EventObserver $observer
     * @return $this
     */
    public function execute(EventObserver $observer)
    {
        if($observer->getElementName() == 'sales.order.info') {
            $orderShippingViewBlock = $observer->getLayout()->getBlock($observer->getElementName());
            $order = $orderShippingViewBlock->getOrder();

            /** @var \Magento\Framework\View\Element\Template $gstNumberBlock */
            $gstNumberBlock = $this->templateFactory->create();
            $gstNumberBlock->setGstNumber($order->getGstNumber());
            $gstNumberBlock->setTemplate('Magelearn_GstCheckout::order_info_shipping_info.phtml');
            $html = $observer->getTransport()->getOutput() . $gstNumberBlock->toHtml();
            $observer->getTransport()->setOutput($html);
        }

        return $this;
    }
}

Add app/code/Magelearn/GstCheckout/view/frontend/templates/order_info_shipping_info.phtml file.

<div id="gst-number">
    <strong><?= __('GST Number') ?>:</strong>
    <br/>
    <span class="price"><?= $block->getGstNumber() ?></span>
</div>
<script type="text/javascript">
    require(
        ['jquery'],
        function($) {
            var element = $('#gst-number').detach();
            $('.box-order-shipping-method').append(element);
        }
    );
</script>

After adding above files, you can find that new field `gst_number` will be added in shipping address form on checkout page. it will be display when you click on new shipping address.

It will also display on admin when you are going to create order from admin.

And also will display on frontend order view page.

1 Comments On "Add Custom Checkout field GST Number in Shipping Address information form in Magento2"
This comment has been removed by the author. - Hapus

Back To Top