In this tutorial, Today I will explain to how to pass custom data in checkout in Magento 2. In checkout page, sometimes we need to pass some custom data to display or add data on checkout page. So, we need to use Magento\Checkout\Model\CompositeConfigProvider class to pass custom variables on checkout page.
Let’s see the following steps to pass data in checkout page :
You may also like this :
- How to Move Apply Coupon To Order Summary in Magento 2
- Magento 2 : Move cart total below cart items in checkout page
1) First of all, let’s assume that you have simple module. Add this below code in app/code/RH/CustomCheckout/etc/frontend/di.xml file :
<?xml version="1.0"?>
<!--
/**
* Created By : Rohan Hapani
*/
-->
<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="custom_data_checkout" xsi:type="object">RH\CustomCheckout\Model\CustomConfigProvider</item>
</argument>
</arguments>
</type>
</config>
2) After that, You need to create app/code/RH/CustomCheckout/Model/CustomConfigProvider.php file and paste the below code to add custom value :
<?php
/**
* Created By : Rohan Hapani
*/
namespace RH\CustomCheckout\Model;
use \Magento\Checkout\Model\ConfigProviderInterface;
class CustomConfigProvider implements ConfigProviderInterface
{
public function getConfig()
{
$configArray = [];
$configArray['custom_data_checkout'] = 'Test Value';
return $configArray;
}
}
Here, you need to implement Magento\Checkout\Model\ConfigProviderInterface interface in custom file to pass custom value in checkout config.
Now, you need to flush cache and then, you can access this value in JS file on checkout page using this below way :
window.checkoutConfig.custom_data_checkout
It will return value : Test Value
That’s it !!!
I hope this blog is easy to understand about how to pass custom data in checkout in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.
Stay Safe and Stay Connected !!