11

I need to add two custom fields in each shipping and payment steps of checkout page in Magento 2 and also data should be saved in needed tables

how to do it in Magento 2

17

Today I am going to explain how to add custom fields to all steps of checkout page and save it after order is placed and also how to use posted data after placing order

1st fields delivery_date :- where customer will mention at the delivery date in shipping step

2nd fields order Comments :- will be in Payment step and after placing order this comments will be add to order comment history

Step 1 :- make sure delivery_date is added in all need table like quote, sales_order and sales_order_grid through install or upgrade script

<?php

namespace Sugarcode\Deliverydate\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

/**
 * @codeCoverageIgnore
 */
class InstallSchema implements InstallSchemaInterface
{

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();

        $installer->getConnection()->addColumn(
            $installer->getTable('quote'),
            'delivery_date',
            [
                'type' => 'datetime',
                'nullable' => false,
                'comment' => 'Delivery Date',
            ]
        );

        $installer->getConnection()->addColumn(
            $installer->getTable('sales_order'),
            'delivery_date',
            [
                'type' => 'datetime',
                'nullable' => false,
                'comment' => 'Delivery Date',
            ]
        );

        $installer->getConnection()->addColumn(
            $installer->getTable('sales_order_grid'),
            'delivery_date',
            [
                'type' => 'datetime',
                'nullable' => false,
                'comment' => 'Delivery Date',
            ]
        );

        $setup->endSetup();
    }
}

Step 2 :- Adding custom fields in shipping and payment steps , we can achieve in two way one from layout xml and other one is plugin below is the way how to add the fields through plugin

We create a di.xml file in our module - Sugarcode/Deliverydate/etc/frontend/di.xml

We use the frontend area to keep it clean, our plugin should run only on the frontend.

<?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="add-delivery-date-field"
                type="Sugarcode\Deliverydate\Model\Checkout\LayoutProcessorPlugin" sortOrder="10"/>
    </type>
</config>

Sugarcode\Plugin\Checkout\LayoutProcessor.php

<?php
namespace Sugarcode\Plugin\Checkout;


class LayoutProcessor
{

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $checkoutSession;

    /**
     * @var \Magento\Customer\Model\AddressFactory
     */
    protected $customerAddressFactory;

    /**
     * @var \Magento\Framework\Data\Form\FormKey
     */
    protected $formKey;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\CheckoutAgreements\Model\ResourceModel\Agreement\CollectionFactory $agreementCollectionFactory,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Customer\Model\AddressFactory $customerAddressFactory
    ) {
        $this->scopeConfig = $context->getScopeConfig();
        $this->checkoutSession = $checkoutSession;
        $this->customerAddressFactory = $customerAddressFactory;
    }
    /**
     * @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
     * @param array $jsLayout
     * @return array
     */
    public function afterProcess(
        \Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
        array  $jsLayout
    ) {
        $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']
        ['shippingAddress']['children']['before-form']['children']['delivery_date'] = [
             'component' => 'Magento_Ui/js/form/element/abstract',
            'config' => [
                'customScope' => 'shippingAddress',
                'template' => 'ui/form/field',
                'elementTmpl' => 'ui/form/element/date',
                'options' => [],
                'id' => 'delivery-date'
            ],
            'dataScope' => 'shippingAddress.delivery_date',
            'label' => 'Delivery Date',
            'provider' => 'checkoutProvider',
            'visible' => true,
            'validation' => [],
            'sortOrder' => 200,
            'id' => 'delivery-date'
        ];


            $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']
            ['payment']['children']['payments-list']['children']['before-place-order']['children']['comment'] = [
                'component' => 'Magento_Ui/js/form/element/textarea',
                'config' => [
                    'customScope' => 'shippingAddress',
                    'template' => 'ui/form/field',
                    'options' => [],
                    'id' => 'comment'
                ],
                'dataScope' => 'ordercomment.comment',
                'label' => 'Order Comment',
                'notice' => __('Comments'),
                'provider' => 'checkoutProvider',
                'visible' => true,
                'sortOrder' => 250,
                'id' => 'comment'
            ];

        return $jsLayout;
    }


}

Now all the fields are in checkout page , now how to save the data

unlike M1 in M2 all Checkout page is completely knockout JS and API

We have two steps first one is shipping and second step is payment where we need to save both fields

Below is how to save the data after shipping addresses are saved

Shipping Step

To save shipping information in M2 uses

app/code/Magento/Checkout/view/frontend/web/js/model/shipping-save-processor/default.js

to prepare json and the call api so we need to override this js and in php side save will happened

\Magento\Checkout\Model\ShippingInformationManagement::SaveAddressInformation() and ShippingInformationManagement implemented by Magento\Checkout\Api\Data\ShippingInformationInterface

M2 has one powerful concept called extension_attributes which is used for dynamic data to core tables lets make it use of that

step 3 :- create a file Deliverydate/etc/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="delivery_date" type="string"/>
    </extension_attributes>
    <extension_attributes for="Magento\Quote\Api\Data\PaymentInterface">
        <attribute code="comment" type="string"/>
    </extension_attributes>
</config>

to override js create a js file Deliverydate/view/frontend/requirejs-config.js we need to use mixns

var config = {
config: {
    mixins: {
        'Magento_Checkout/js/action/place-order': {
            'Sugarcode_Deliverydate/js/order/place-order-mixin': true
        },
        'Magento_Checkout/js/action/set-payment-information': {
            'Sugarcode_Deliverydate/js/order/set-payment-information-mixin': true
        },
        'Magento_Checkout/js/action/set-shipping-information': {
            'Sugarcode_Deliverydate/js/order/set-shipping-information-mixin': true
        }
    }
};

js/order/set-shipping-information-mixin.js delivery_date

/**
 * @author aakimov
 */
/*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'] = {};
            }

            // you can extract value of extension attribute from any place (in this example I use customAttributes approach)
            shippingAddress['extension_attributes']['delivery_date'] = jQuery('[name="delivery_date"]').val();
            // pass execution to original action ('Magento_Checkout/js/action/set-shipping-information')
            return originalAction();
        });
    };
});

The next step is saving this custom field post data to the quote. Let's make another plugin by adding an xml node in our etc/di.xml

<type name="Magento\Checkout\Model\ShippingInformationManagement">
        <plugin name="save-in-quote" type="Sugarcode\Deliverydate\Model\Checkout\ShippingInformationManagementPlugin" sortOrder="10"/>
</type>

Create a file Sugarcode\Deliverydate\Plugin\Checkout\ShippingInformationManagementPlugin.php

<?php

namespace Sugarcode\Deliverydate\Plugin\Checkout;

class ShippingInformationManagementPlugin
{

    protected $quoteRepository;

    public function __construct(
        \Magento\Quote\Model\QuoteRepository $quoteRepository
    ) {
        $this->quoteRepository = $quoteRepository;
    }

    /**
     * @param \Magento\Checkout\Model\ShippingInformationManagement $subject
     * @param $cartId
     * @param \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
     */
    public function beforeSaveAddressInformation(
        \Magento\Checkout\Model\ShippingInformationManagement $subject,
        $cartId,
        \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
    ) {
        $extAttributes = $addressInformation->getShippingAddress()->getExtensionAttributes();
        $deliveryDate = $extAttributes->getDeliveryDate();
        $quote = $this->quoteRepository->getActive($cartId);
        $quote->setDeliveryDate($deliveryDate);
    }
}

soon after when you move to payment steps data will be saved in quote table

to save same data after placing order we need to use fieldset

etc/fieldset.xml

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

Now lets Save the payment steps field

if we have extra fields in payment step and we need to post that data then we need to override the other js as we done for shipping step

as like shipping information we have payment information

ww can achive by override is Magento_Checkout/js/action/place-order.js (but it will have issue when agreement is enabled so we need to use mixins as mention in re)

Sugarcode_Deliverydate/js/order/place-order-mixin.js


/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define([
    'jquery',
    'mage/utils/wrapper',
    'Sugarcode_Deliverydate/js/order/ordercomment-assigner'
], function ($, wrapper, ordercommentAssigner) {
    'use strict';

    return function (placeOrderAction) {

        /** Override default place order action and add comments to request */
        return wrapper.wrap(placeOrderAction, function (originalAction, paymentData, messageContainer) {
            ordercommentAssigner(paymentData);

            return originalAction(paymentData, messageContainer);
        });
    };
});

Sugarcode_Deliverydate/js/order/ordercomment-assigner.js

/*jshint browser:true jquery:true*/
/*global alert*/
define([
    'jquery'
], function ($) {
    'use strict';


    /** Override default place order action and add comment to request */
    return function (paymentData) {

        if (paymentData['extension_attributes'] === undefined) {
            paymentData['extension_attributes'] = {};
        }

        paymentData['extension_attributes']['comment'] = jQuery('[name="ordercomment[comment]"]').val();
    };
});

Sugarcode_Deliverydate/js/order/set-payment-information-mixin.js

/*jshint browser:true jquery:true*/
/*global alert*/
define([
    'jquery',
    'mage/utils/wrapper',
    'Sugarcode_Deliverydate/js/order/ordercomment-assigner'
], function ($, wrapper, ordercommentAssigner) {
    'use strict';

    return function (placeOrderAction) {

        /** Override place-order-mixin for set-payment-information action as they differs only by method signature */
        return wrapper.wrap(placeOrderAction, function (originalAction, messageContainer, paymentData) {
            ordercommentAssigner(paymentData);

            return originalAction(messageContainer, paymentData);
        });
    };
});

and need to create a plugin for Magento\Checkout\Model\PaymentInformationManagement

so in etc/di add below code

 <type name="Magento\Checkout\Model\PaymentInformationManagement">
        <plugin name="order_comments_save-in-order" type="Sugarcode\Deliverydate\Plugin\Checkout\PaymentInformationManagementPlugin" sortOrder="10"/>
    </type>

and then create a file Sugarcode\Deliverydate\Plugin\Checkout\PaymentInformationManagementPlugin.php

/**
 * One page checkout processing model
 */
class PaymentInformationManagementPlugin
{

    protected $orderRepository;

    public function __construct(
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
    ) {
        $this->orderRepository = $orderRepository;
    }


    public function aroundSavePaymentInformationAndPlaceOrder(
        \Magento\Checkout\Model\PaymentInformationManagement $subject,
        \Closure $proceed,
        $cartId,
        \Magento\Quote\Api\Data\PaymentInterface $paymentMethod,
        \Magento\Quote\Api\Data\AddressInterface $billingAddress = null
    ) {
        $result = $proceed($cartId, $paymentMethod, $billingAddress);

         if($result){

            $orderComment =$paymentMethod->getExtensionAttributes();
             if ($orderComment->getComment())
               $comment = trim($orderComment->getComment());
           else
               $comment = ''; 


            $history = $order->addStatusHistoryComment($comment);
            $history->save();
            $order->setCustomerNote($comment);                
         }

        return $result;
    }
}

Note :- if the field in payment step need to save in quote table then use beofore plugin for same function and follow as did in ShippingInformationManagementPlugin

  • Referring to you Step 1, where should this file reside? And how it will be executed? As its required just one time. – Abdul Moiz Oct 3 '17 at 13:21
  • And are you sure this would work for adding form in my custom step, because you referring to magento's build in checkout steps. – Abdul Moiz Oct 3 '17 at 13:22
  • Sugarcode/Deliverydate\Setup:- inside app/code folder FYI Sugarcode :- name space , Deliverydate module name and setup folder is inside Deliverydate , how to install in run upgrade command , if you dont know upgrade command then i feel you are very new in M2 , so please go through basic m2 – Pradeep Kumar Oct 4 '17 at 2:55
  • Thanks, how can i modify it to add form on a new step. That i have already added? – Abdul Moiz Oct 4 '17 at 7:39
  • if its all together new steps like shipping and payment steps then need to check create new ticket or question – Pradeep Kumar Oct 5 '17 at 8:21
1

Before doing customizations, do the following.

  • Set Magento to developer mode
  • Do not edit default Magento code, instead add customizations in a separate module
  • Do not use Ui for your custom module name

Step 1: Create the JS implementation of the form UI component

In your <your_module_dir>/view/frontend/web/js/view/ directory, create a .js file implementing the form.

/*global define*/
define([
    'Magento_Ui/js/form/form'
], function(Component) {
    'use strict';
    return Component.extend({
        initialize: function () {
            this._super();
            // component initialization logic
            return this;
        },

        /**
         * Form submit handler
         *
         * This method can have any name.
         */
        onSubmit: function() {
            // trigger form validation
            this.source.set('params.invalid', false);
            this.source.trigger('customCheckoutForm.data.validate');

            // verify that form data is valid
            if (!this.source.get('params.invalid')) {
                // data is retrieved from data provider by value of the customScope property
                var formData = this.source.get('customCheckoutForm');
                // do something with form data
                console.dir(formData);
            }
        }
    });
});

Step 2: Create the HTML template

Add the knockout.js HTML template for the form component under the <your_module_dir>/view/frontend/web/template directory.

Example:

<div>
    <form id="custom-checkout-form" class="form" data-bind="attr: {'data-hasrequired': $t('* Required Fields')}">
        <fieldset class="fieldset">
            <legend data-bind="i18n: 'Custom Checkout Form'"></legend>
            <!-- ko foreach: getRegion('custom-checkout-form-fields') -->
            <!-- ko template: getTemplate() --><!-- /ko -->
            <!--/ko-->
        </fieldset>
        <button type="reset">
            <span data-bind="i18n: 'Reset'"></span>
        </button>
        <button type="button" data-bind="click: onSubmit" class="action">
            <span data-bind="i18n: 'Submit'"></span>
        </button>
    </form>
</div>

Clear files after modification

If you modify your custom .html template after it was applied on the store pages, the changes will not apply until you do the following:

Delete all files in the pub/static/frontend and var/view_preprocessed directories. Reload the pages.

Step 3: Declare the form in the checkout page layout

To add content to the Shipping Information step, create a checkout_index_index.xml layout update in the <your_module_dir>/view/frontend/layout/.

It should be similar to the following.

<?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="checkout.root">
            <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="components" xsi:type="array">
                        <item name="checkout" xsi:type="array">
                            <item name="children" xsi:type="array">
                                <item name="steps" xsi:type="array">
                                    <item name="children" xsi:type="array">
                                        <item name="shipping-step" xsi:type="array">
                                            <item name="children" xsi:type="array">
                                                <item name="shippingAddress" xsi:type="array">
                                                    <item name="children" xsi:type="array">
                                                        <item name="before-form" xsi:type="array">
                                                            <item name="children" xsi:type="array">
                                                                <!-- Your form declaration here -->
                                                            </item>
                                                        </item>
                                                    </item>
                                                </item>
                                            </item>
                                        </item>
                                    </item>
                                </item>
                            </item>
                        </item>
                    </item>
                </argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

Static forms:

The following code sample shows configuration of the form that contains four fields: text input, select, checkbox, and date. This form uses checkout data provider (checkoutProvider) that is introduced in the Magento_Checkout module:

<item name="custom-checkout-form-container" xsi:type="array">
    <item name="component" xsi:type="string">%your_module_dir%/js/view/custom-checkout-form</item>
    <item name="provider" xsi:type="string">checkoutProvider</item>
    <item name="config" xsi:type="array">
        <item name="template" xsi:type="string">%your_module_dir%/custom-checkout-form</item>
    </item>
    <item name="children" xsi:type="array">
        <item name="custom-checkout-form-fieldset" xsi:type="array">
            <!-- uiComponent is used as a wrapper for form fields (its template will render all children as a list) -->
            <item name="component" xsi:type="string">uiComponent</item>
            <!-- the following display area is used in template (see below) -->
            <item name="displayArea" xsi:type="string">custom-checkout-form-fields</item>
            <item name="children" xsi:type="array">
                <item name="text_field" xsi:type="array">
                    <item name="component" xsi:type="string">Magento_Ui/js/form/element/abstract</item>
                    <item name="config" xsi:type="array">
                        <!-- customScope is used to group elements within a single form (e.g. they can be validated separately) -->
                        <item name="customScope" xsi:type="string">customCheckoutForm</item>
                        <item name="template" xsi:type="string">ui/form/field</item>
                        <item name="elementTmpl" xsi:type="string">ui/form/element/input</item>
                    </item>
                    <item name="provider" xsi:type="string">checkoutProvider</item>
                    <item name="dataScope" xsi:type="string">customCheckoutForm.text_field</item>
                    <item name="label" xsi:type="string">Text Field</item>
                    <item name="sortOrder" xsi:type="string">1</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="string">true</item>
                    </item>
                </item>
                <item name="checkbox_field" xsi:type="array">
                    <item name="component" xsi:type="string">Magento_Ui/js/form/element/boolean</item>
                    <item name="config" xsi:type="array">
                        <!--customScope is used to group elements within a single form (e.g. they can be validated separately)-->
                        <item name="customScope" xsi:type="string">customCheckoutForm</item>
                        <item name="template" xsi:type="string">ui/form/field</item>
                        <item name="elementTmpl" xsi:type="string">ui/form/element/checkbox</item>
                    </item>
                    <item name="provider" xsi:type="string">checkoutProvider</item>
                    <item name="dataScope" xsi:type="string">customCheckoutForm.checkbox_field</item>
                    <item name="label" xsi:type="string">Checkbox Field</item>
                    <item name="sortOrder" xsi:type="string">3</item>
                </item>
                <item name="select_field" xsi:type="array">
                    <item name="component" xsi:type="string">Magento_Ui/js/form/element/select</item>
                    <item name="config" xsi:type="array">
                        <!--customScope is used to group elements within a single form (e.g. they can be validated separately)-->
                        <item name="customScope" xsi:type="string">customCheckoutForm</item>
                        <item name="template" xsi:type="string">ui/form/field</item>
                        <item name="elementTmpl" xsi:type="string">ui/form/element/select</item>
                    </item>
                    <item name="options" xsi:type="array">
                        <item name="0" xsi:type="array">
                            <item name="label" xsi:type="string">Please select value</item>
                            <item name="value" xsi:type="string"></item>
                        </item>
                        <item name="1" xsi:type="array">
                            <item name="label" xsi:type="string">Value 1</item>
                            <item name="value" xsi:type="string">value_1</item>
                        </item>
                        <item name="2" xsi:type="array">
                            <item name="label" xsi:type="string">Value 2</item>
                            <item name="value" xsi:type="string">value_2</item>
                        </item>
                    </item>
                    <!-- value element allows to specify default value of the form field -->
                    <item name="value" xsi:type="string">value_2</item>
                    <item name="provider" xsi:type="string">checkoutProvider</item>
                    <item name="dataScope" xsi:type="string">customCheckoutForm.select_field</item>
                    <item name="label" xsi:type="string">Select Field</item>
                    <item name="sortOrder" xsi:type="string">2</item>
                </item>
                <item name="date_field" xsi:type="array">
                    <item name="component" xsi:type="string">Magento_Ui/js/form/element/date</item>
                    <item name="config" xsi:type="array">
                        <!--customScope is used to group elements within a single form (e.g. they can be validated separately)-->
                        <item name="customScope" xsi:type="string">customCheckoutForm</item>
                        <item name="template" xsi:type="string">ui/form/field</item>
                        <item name="elementTmpl" xsi:type="string">ui/form/element/date</item>
                    </item>
                    <item name="provider" xsi:type="string">checkoutProvider</item>
                    <item name="dataScope" xsi:type="string">customCheckoutForm.date_field</item>
                    <item name="label" xsi:type="string">Date Field</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="string">true</item>
                    </item>
                </item>
            </item>
        </item>
    </item>
</item>

Hope this helps.

  • you added Static forms code, what will be its file name and where will it be placed? – Sanaullah Ahmad Sep 24 at 11:18
  • @SanaullahAhmad there is an easy way too i.e. to use a module like this one. – Henry Roger Oct 11 at 12:45
0

Don't Try long solutions. Just download and install this magento2 module from github and you will see custom fields in checkout page. https://github.com/magentodevblog/magento-2-add-custom-field-in-checkout-shipping

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.