How to Add Custom Field to Magento 2 Shipping Address

In some cases, Magento 2 merchants want to customize their checkout page according to their requirements and user expectations. Here we will walk you through the steps required to add custom field to the checkout shipping address form and also get its value on the client side.

Adding Custom Field to Magento 2 Shipping Address Programmatically

First, let’s see how to do it programmatically.

Step 1: Add the Field to Layout

As both shipping and billing address forms are generated dynamically, we have to create a plugin to modify their layouts. We will create this plugin for the \Magento\Checkout\Block\Checkout\LayoutProcessor::process method and declare it in the di.xml file. Following is the code for adding a ‘Custom Shipping Attribute’ field to the shipping address form.

Magento_Checkout/js/action/set-shipping-information is the component that does the data submission between Magento 2 shipping and billing checkout steps. The following code modifies the behavior of the component.

<?php
$customshippingAttribute = 'custom_field';					
$customField = [
    'component' => 'Magento_Ui/js/form/element/abstract',
    'config' => [
        // customScope is used to group elements within a single form (e.g. they can be validated separately)
        'customScope' => 'shippingAddress.custom_attributes',
        'customEntry' => null,
        'template' => 'ui/form/field',
        'elementTmpl' => 'ui/form/element/input',
        'tooltip' => [
            'description' => 'this is what the field is for',
        ],
    ],
    'dataScope' => 'shippingAddress.custom_attributes' . '.' . $customshippingAttribute,
    'label' => 'Custom Shipping Attribute',
    'provider' => 'checkoutProvider',
    'sortOrder' => 0,
    'validation' => [
       'required-entry' => true
    ],
    'options' => [],
    'filterBy' => null,
    'customEntry' => null,
    'visible' => true,
];

$jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children'][$customshippingAttribute] = $customField;

$jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children'][$customShippingAttributeCode] = $customField;
Step 2: Modify the Behavior of the Data Submission Component

Magento_Checkout/js/action/set-shipping-information is the component that does the data submission between Magento 2 shipping and billing checkout steps. The following code modifies the behavior of the component.

/*jshint browser:true jquery:true*/
/*global alert*/
define([
    'jquery',
    'mage/utils/wrapper',
    'Magento_Checkout/js/model/quote'
], function ($, wrapper, quote) {
    'use strict';

    return function (setShippingInformationAction) {

        return wrapper.wrap(setShippingInformationAction, function (originalAction) {
            var shippingAddress = quote.shippingAddress();
            if (shippingAddress['extension_attributes'] === undefined) {
                shippingAddress['extension_attributes'] = {};
            }

            shippingAddress['extension_attributes']['custom_field'] = shippingAddress.customAttributes['custom_field'];
            // pass execution to original action ('Magento_Checkout/js/action/set-shipping-information')
            return originalAction();
        });
    };
});


Step 3: Load Your Mixin

Use the code below to load your mixin for the corresponding JS component by adding the requirejs-config.js to the /view/frontend/ directory.

var config = {
config: {
mixins: {
'Magento_Checkout/js/action/set-shipping-information': {
'/js/action/set-shipping-information-mixin': true
}
}
}
};
Step 4: Add Field to Address Model

To do so, add the extension_attributes.xml file in the /etc/ directory.


<?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="custom_field" type="string" />    </extension_attributes></config>
Step 5: Get the Value of the Custom Field

Create an instance of the Magento/Quote/Api/Data/AddressInterface.php interface to set/get values of the custom fields.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$addressInformation = $objectManager->create('Magento\Checkout\Api\Data\ShippingInformationInterface');
$extAttributes = $addressInformation->getExtensionAttributes();
$selectedShipping = $extAttributes->getCustomShippingCharge(); //get custom attribute data.

Adding Custom Field to Magento 2 Shipping Address Using Extension

To make life easier, FMEextensions offers a useful tool to let merchants add custom fields to any checkout step. The following demo image displays how they can choose a checkout step to add the custom field to. Just select ‘Shipping Address’ in the dropdown and the field will be displayed in the shipping address form.

Magento 2 add custom field to checkout

As can be seen, two mandatory custom fields ‘Choose Delivery Date’ & ‘Choose Delivery Time-Multiselect’ have been added to the shipping address section.

Magento 2 add field to shipping address

View Extension Demos:  Frontend Demo     Backend Demo     Buy Extension