Site icon MageComp Blog

Magento 2: How to Access Configuration Variables in Checkout Javascript Files?

How to Access Configuration Variables in Checkout Javascript Files in M2

Hello Magento Friends,

This article is about Magento 2: How to Access Configuration Variables in Checkout Javascript Files?

Sometimes the user needs to add some custom variables to the checkout page and can use it to develop some custom functionality or implement some custom code in Magento 2. Here is how you can Access Configuration Variables in Checkout Javascript Files in Magento 2.

Steps to Access Configuration Variables in Checkout Javascript Files in Magento 2:

Step 1: First, we need to create a “di.xml” file inside our extension at the following path.

app\code\Vendor\Extension\etc\

Now, add the code as follows

<?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="custom_config_provider" xsi:type="object">Vendor\Extension\Model\ConfigProvider</item>
            </argument>
        </arguments>
    </type>
</config>

Step 2: After that, we need to create a “ConfigProvider.php” file inside the extension Model directory

app\code\Vendor\Extension\Model\

And add the below-mentioned code

<?php
namespace Vendor\Extension\Model;

use Magento\Checkout\Model\ConfigProviderInterface;
use Magento\Framework\View\LayoutInterface;

class ConfigProvider implements ConfigProviderInterface
{
    /** @var LayoutInterface  */
    protected $_layout;

    public function __construct(LayoutInterface $layout)
    {
        $this->_layout = $layout;
    }

    /**
     * {@inheritdoc}
     */
    public function getConfig()
    { 
        $config = [
            'payment' => [    
                'custom_config' => [/*Add your custom variables here*/
                    'redirectUrl' => 'www.google.com',
                ]
            ]
        ];
        return $config;
    }
}

Step 3: After that, you can access this from checkout javascript files in the following way

//var redirectUrl = window.checkoutConfig.payment.custom_config.redirectUrl;
console.log(window.checkoutConfig.payment.custom_config.redirectUrl);

Conclusion:

With the help of these steps, you can successfully achieve the task to Access Configuration Variables in Checkout Javascript Files in Magento 2. If you face any issues while implementing, then mention them in the comment box or contact our support team. We will be happy to help you.

Besides this, you can also Get System Configuration Value Into JS in Magento 2. Do not forget to spread this article to your Magento group. Catch you next time, till then remain connected with us!

Happy Coding!

Exit mobile version