Pre Black Friday Sale. 20% OFF on all products. Coupon code: fme20off

How to Add Custom Fields in Magento 2 Checkout Page Programmatically?

How to Add Custom Fields in Magento 2 Checkout Page Programmatically?

The checkout page is the most important page in an online store. This page determines whether the user will convert to a customer, or they’ll abandon their cart. One may think that if a customer has gone through hours of product research and ended up finalising a product, they have all the reasons to buy it.

However, it is not the case as the user is more likely to abandon the cart rather than complete the purchase. This is not something we have come up with ourselves. Instead, it is based on evidence. The below statistic shows the global digital cart abandonment rate. What do you notice?

cart-abandon

Source: Statista

The current cart abandonment rate stands at 70.01%. In other words, for every 100 users who add a product to the cart, 70 will abandon it. The above statistic has been compiled in cooperation with the Baymard Institute. Hence, there’s no doubting its credibility since their stats are based on 150,000+ hours of UX research.

One of the top reasons behind cart abandonment is a complex checkout process. If there are too many fields to fill or unnecessary steps, users will be left frustrated. Thus, merchants need to customise the checkout form. They need to ensure a balance between their own requirements and user satisfaction.

In this article, we will go through the process of how to add custom fields in Magento 2 checkout page.

Why Set Up Magento 2 Custom Checkout Fields

Apart from the cart abandonment issue, there are several other reasons to customise the checkout fields in Magento 2. Let’s go through them.

Additional Customer Information

You can use the checkout fields to collect additional information from the customers. For example, you can ask them information such as ‘where you heard about us?’. You can use the data from this field to make changes to your marketing strategy. For example, if most people selected social media, it shows that other strategies such as SEO are proving ineffective.

Targeted Marketing

Similarly, you can use the custom checkout fields to know more about the customer’s preferences. This can help refine your targeted marketing strategies and improve the conversion rate.

Order Fulfilment

Store owners face numerous challenges, including failed deliveries. If a customer isn’t available, the order is likely to be returned to the sender. This impacts user satisfaction and adds to the store’s expenses. A custom checkout field can be set up to ask the customer about preferred delivery day and time. This reduces the risk of failed delivery, thereby ensuring smoother order fulfilment process.

Methods to Add Custom Fields in Magento 2 Checkout

Whether you wish to configure Magento 2 add custom field to shipping method or any other stage of the checkout process, there are two ways to do so:

  • Custom Module or Programmatically
  • Using an Extension

Magento 2 does not have an in-built feature for customising the checkout fields. What little features it does offer, they are quite limited. The lack of customisability and flexibility force merchants to opt for either one of the above two options. Let’s explore them in further detail to gain a better understanding.

Method 1: Add Custom Field in Checkout Page Magento 2 Programmatically

Step 1: Create a Custom Module

First, create a folder using the following code:

app/code/Vendor/CheckoutField

Step 2: Register the Module

Create registration.php under app/code/Vendor/CheckoutField/registration.php and add the following code:

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_CheckoutField',
    __DIR__
);

Step 3: Create the module.xml file

Create the file in app/code/Vendor/CheckoutField/etc/module.xml by using the below code:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
   <module name="Vendor_CheckoutField" setup_version="1.0.0"/>
</config>

Step 4: Enable the Module

Enter the following command in the terminal

php bin/magento setup:upgrade
php bin/magento cache:flush

Step 5: Edit the Layout File

Create the layout file in app/code/Vendor/CheckoutField/view/frontend/layout/checkout_index_index.xml and enter the following code:

<?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>
       <referenceContainer name="checkout.root">
            <block name="checkout.field" before="-" template="Vendor_CheckoutField::checkout/field.phtml" />
        </referenceContainer>
    </body>
</page>

Step 6: Create the Custom Field Template

Create the field.phtml file: In app/code/Vendor/CheckoutField/view/frontend/templates/checkout/field.phtml and add:

<div class="field custom-field">
    <label><?= __('Custom Field') ?></label>
    <input type="text" name="custom_field" id="custom_field" data-bind="value: customField"/>
</div>

Step 7: Add Custom Field to JavaScript Component

Create custom_field.js in the web directory: In app/code/Vendor/CheckoutField/view/frontend/web/js/view/custom_field.js and add:

define([
    'uiComponent',
    'ko'
], function (Component, ko) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Vendor_CheckoutField/checkout/field'
        },
        customField: ko.observable(''),
        initialize: function () {
            this._super();
        }
    });
});

Step 8: Configure JavaScript

Configure JavaScript in the requirejs-config.js: In app/code/Vendor/CheckoutField/view/frontend/requirejs-config.js, add:

var config = {
    config: {
        mixins: {
            'Magento_Checkout/js/view/shipping': {
                'Vendor_CheckoutField/js/view/custom_field': true
            }
        }
    }
};

Step 9: Save Custom Field Value to Order Data

Create the events.xml file: In app/code/Vendor/CheckoutField/etc/frontend/events.xml, add:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework/Event/etc/events.xsd">
    <event name="checkout_submit_all_after">
        <observer name="vendor_checkoutfield_save_custom_field" instance="Vendor\CheckoutField\Observer\SaveCustomFieldObserver"/>
    </event>
</config>

Step 10: Create the Observer File

Create it in app/code/Vendor/CheckoutField/Observer/SaveCustomFieldObserver.php, add:

getEvent()->getOrder();
        $customFieldValue = $observer->getEvent()->getRequest()->getParam('custom_field');

        if ($customFieldValue) {
            $order->setData('custom_field', $customFieldValue);
            $order->save();
        }
    }
}

Step 11: Add Custom Field to Database Schema

Create the InstallData.php file: In app/code/Vendor/CheckoutField/Setup/InstallData.php, add:

startSetup();
        $setup->getConnection()->addColumn(
            $setup->getTable('sales_order'),
            'custom_field',
            [
                'type' => Table::TYPE_TEXT,
                'length' => 255,
                'nullable' => true,
                'comment' => 'Custom Field'
            ]
        );
        $setup->endSetup();
    }
}

Step 12: Run the setup upgrade command:

php bin/magento setup:upgrade

Step 13: Test the module and ensure it works as desired.

Method 2: Magento 2 Custom Checkout Fields Extension

As you can see for yourself, there are too many steps when trying to add custom fields to the checkout process programmatically. There is a risk of things going drastically wrong, preventing users from completing the checkout process altogether. Apart from it, you’ll need to rework the code to ensure it remains compatible with the latest Magento versions. Thus, it is better to use an extension.

A Magento 2 Custom Checkout Fields Extension such as one by FME allows users to customise the checkout fields without any technical knowledge. All they need to do is install the extension, configure it, and then make changes from the admin panel. Additionally, users don’t have to worry about updating the code to ensure that it remains compatible with the latest version of Magento.

Final Thoughts on Adding Custom Fields in Magento 2 Checkout Programmatically

This concludes our guide on adding custom fields in Magento 2 checkout page. If you have a dedicated Magento development team, you can opt for custom development. Otherwise, the extension offers a quick and reliable way to customise the checkout page. If you have any questions regarding FME’s Magento 2 Custom Checkout Field Extension, don’t hesitate to reach out to our support team.

This blog was created with FME's SEO-friendly blog