In this blog, we will learn how to pass custom data in checkout in Magento 2. On the checkout page, sometimes we need to pass some custom data to display or add data at the time of the checkout process. So, we need to use Magento\Checkout\Model\CompositeConfigProvider class to pass custom variables 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, then you have to add the below code in the app/code/Webkul/CustomCheckoutData/etc/frontend/di.xml file :
<?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" xsi:type="object">Webkul\CustomCheckoutData\Model\CheckoutConfigProvider</item> </argument> </arguments> </type> </config>
Step 2: After that, You need to create an app/code/Webkul/CustomCheckoutData/Model/CustomConfigProvider.php file and paste the below code to add a custom value :
<?php namespace Webkul\CustomCheckoutData\Model; use \Magento\Checkout\Model\ConfigProviderInterface class CheckoutConfigProvider implements ConfigProviderInterface { public function getConfig() { $configArray = []; $configArray['custom_data'] = 'Webkul Test Value'; return $configArray; } }
Here, you need to implement the Magento\Checkout\Model\ConfigProviderInterface interface in a custom file to pass a custom value in the checkout config.
Now, you need to flush the cache and then, you can access this value in the JS file on the checkout page using the below way :
window.checkoutConfig.custom_data
Output:
We hope this tutorial is useful for you.
You may like our other tutorials :
Custom Checkout step in Magento 2
Be the first to comment.