Question

I found that all knockout JS config data are coming from window.checkoutConfig.

Then I check onepage.phtml and found that they used this code to store data in window.checkoutConfig

window.checkoutConfig = <?php /* @escapeNotVerified */ echo \Zend_Json::encode($block->getCheckoutConfig()); ?>;

So my question is that how we add our custom data in window.checkoutConfig and use in checkout knockout js like this

var customData = window.checkoutConfig.myCustomData;

alert(customData);
Was it helpful?

Solution

You have to just override getConfig() function of checkout module.

app/code/Packagename/Checkout/etc/frontend/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <!-- pass custom variable to checkout page -->
    <type name="Magento\Checkout\Model\CompositeConfigProvider">
        <arguments>
            <argument name="configProviders" xsi:type="array">
                <item name="checkout_custom_shipping_block" xsi:type="object">Packagename\Checkout\Model\CustomConfigProvider</item>
            </argument>
        </arguments>
    </type>
</config>

app/code/Packagename/Checkout/Model/CustomConfigProvider.php file,

<?php
namespace Packagename\Checkout\Model;

use Magento\Checkout\Model\ConfigProviderInterface;

class CustomConfigProvider implements ConfigProviderInterface
{
    public function getConfig()
    {
        $config = [];
        $config['myCustomData'] = 'your custom value';

        return $config;
    }
}

Clear Cache and remove var/generation folder,

Inside your knockout js file, You can get value like,

var customData = window.checkoutConfig.myCustomData;

alert(customData);
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top