Magento 2: Access Configuration Value in JavaScript at Checkout

Magento 2 Access Configuration Value in JavaScript at Checkout - SbDevBlog

We have accessed the configuration value in the JavaScript widget. In this post, we will access the configuration value in JavaScript at checkout.

As in the last post, if we pass value to a JS widget, we can access value from only that JS. But what if we require access to configuration values throughout checkout? In that case, we must pass an additional class as an argument as configProviders to the below class using the type tag in di.xml.

 Magento\Checkout\Model\CompositeConfigProvider

We must create an additional class in the module, which we have passed as configProviders. We must implement the below interface in our configuration class.

Magento\Checkout\Model\ConfigProviderInterface

Magento 2: Access Configuration Value in JavaScript at Checkout

Created di.xml inside the frontend area of the etc directory of the module.

<?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="additional_provider_class" xsi:type="object">Vendor\ModuleName\Model\AdditionalConfig</item>
            </argument>
        </arguments>
    </type>
</config>

We must create the Configuration Provider class.

<?php
/**
 * @copyright Copyright (c) sbdevblog (http://www.sbdevblog.com)
 */

namespace Vendor\ModuleName\Model;

use Magento\Checkout\Model\ConfigProviderInterface;

class AdditionalConfig implements ConfigProviderInterface
{
    /**
     * @inheritDoc
     */
    public function getConfig()
    {
        $validationConfig = [
            "var_1" => "value_1",
            "var_2" => "value_2",
            "var_3" => "value_3"
        ];

        return $validationConfig;
    }
}

We can use these variables in any JS of the checkout.

window.checkoutConfig.var_1
window.checkoutConfig.var_2
window.checkoutConfig.var_3

That’s it. It is straightforward to access configuration values in the JS of checkout. I want to go ahead and check out the example I created to access configuration values.

I have created a configuration to allow the admin to add a PO box regular expression, which I will use to restrict shipping. In addition, I have created a basic checkout module under the sbdevblog namespace to limit PO box values on the street.

So let’s put di.xml in the frontend directory of the etc directory of the module.

<?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="additional_provider" xsi:type="object">SbDevBlog\Checkout\Model\AdditionalValidationConfig</item>
            </argument>
        </arguments>
    </type>
</config>

Let’s create a service class that allows access to configuration values.

<?php
/**
 * @copyright Copyright (c) sbdevblog (http://www.sbdevblog.com)
 */

namespace SbDevBlog\Checkout\Services;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;

class ValidationConfigurationService
{
    private const ADDITIONAL_VALIDATION_PATH = "sbcheckout/additional_validation/";
    private const ENABLE_VALIDATION_PATH = "enable";
    private const VALIDATION_REGREX_PATH = "pobox_validation_regex";

    /**
     * @var ScopeConfigInterface
     */
    private ScopeConfigInterface $scopeConfig;

    /**
     * Constructor
     *
     * @param ScopeConfigInterface $scopeConfig
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig
    )
    {
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * Get Validation Configuration
     *
     * @return array
     */
    public function getValidationConfig(): array
    {
        return [
            "validation_enable" => $this->getConfig(self::ENABLE_VALIDATION_PATH),
            "validation_regrex" => $this->getConfig(self::VALIDATION_REGREX_PATH)
        ];
    }

    /**
     * Get Configuration value
     *
     * @param string $path
     * @return mixed
     */
    private function getConfig(string $path)
    {
        return $this->scopeConfig->getValue(self::ADDITIONAL_VALIDATION_PATH . $path, ScopeInterface::SCOPE_STORE);
    }
}

Finally, it’s time to create the Configuration Provider class.

<?php
/**
 * @copyright Copyright (c) sbdevblog (http://www.sbdevblog.com)
 */

namespace SbDevBlog\Checkout\Model;

use Magento\Checkout\Model\ConfigProviderInterface;
use SbDevBlog\Checkout\Services\ValidationConfigurationService;

class AdditionalValidationConfig implements ConfigProviderInterface
{
    /**
     * @var ValidationConfigurationService
     */
    private ValidationConfigurationService $validationConfigurationService;

    /**
     * @param ValidationConfigurationService $validationConfigurationService
     */
    public function __construct(
        ValidationConfigurationService $validationConfigurationService
    )
    {
        $this->validationConfigurationService = $validationConfigurationService;
    }

    /**
     * @inheritDoc
     */
    public function getConfig()
    {
        $validationConfiguration = $this->validationConfigurationService->getValidationConfig();
        $validationConfig = [
            "pobox_validation_enabled" => $validationConfiguration["validation_enable"],
            "pobox_validation_regrex" => $validationConfiguration["validation_regrex"]
        ];

        return $validationConfig;
    }
}

That’s it. Thank you for visiting SbDevBlog and reading the post Magento 2: Access Configuration Value in JavaScript at Checkout. Please use the comment box to provide your feedback. Also, please subscribe and share with your connections.

Download Source Code

Note: Please verify the code of this blog and the relevant git repository before using it in production.
sb dev blog adobe commece Magento 2

🙂 HAPPY CODING 🙂

One thought on “Magento 2: Access Configuration Value in JavaScript at Checkout

Leave a Reply

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