How to set custom data in checkout in Magento 2

In this blog, we will learn how to set custom data in checkout in Magento 2

In the checkout page, We mostly need to set custom data that we need to use on the checkout page at the time of checkout process. We need to use the class Magento\Checkout\Model\CompositeConfigProvider to pass custom data on the checkout page.

Let’s start step by step and learn how we can do that.

Step 1: We assume you have created a simple module with required files. Please create file di.xml at path app/code/Mageclues/Checkout/etc/frontend/di.xml and add below code in it.

<?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\CompositeConfigProvider">
        <arguments>
            <argument name="configProviders" xsi:type="array">
                <item name="set_custom_data_in_checkout" xsi:type="object">Mageclues\Checkout\Model\CheckoutConfigProvider</item>
            </argument>
        </arguments>
    </type>
</config>

Step 2: Then, You need to create a class file at path app/code/Mageclues/Checkout/Model/CheckoutConfigProvider.php and paste the below code to set custom value.

<?php

namespace Mageclues\Checkout\Model;

use \Magento\Checkout\Model\ConfigProviderInterface

class CheckoutConfigProvider implements ConfigProviderInterface
{
    public function getConfig()
    {
		$configArray = [];
		$configArray['custom_var'] = 'Test Value';
		return $configArray;
    }
}

Here, we need to implement the Magento\Checkout\Model\ConfigProviderInterface interface in the custom class to set custom data/value in checkout config.

Step 3: Now, you need to flush the cache and after that, we can get this value in the JS file on the checkout page using below syntax.

window.checkoutConfig.custom_var

We hope this tutorial is useful for you. please leave a comment if you have any questions.

Thank You):

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *