How to Pass the System Configuration Value to Knockout?

0

As you know sometime Knockout Component is quite difficult to understand and in Magento 2 Knockout JS is on almost every page which used mostly on the checkout page.

Now, many developers want to pass system configuration value in the knockout component but they don’t know the correct way after finding many solutions so I have just shared with you little logic which helps you in the many different cases.

In this logic, I assume you have already created the module and just follow below simple steps that show you the value which held on the configuration.

Step 1: First, create getConfigurationValue.js file in the following location

app/code/[Namespace]/[Module]/view/frontend/web/js/view/payment/method-renderer/

define(
    [
        'Magento_Checkout/js/view/payment/default',
        'mage/storage',
        'mage/url',
        'jquery',
    ],
    function (Component,storage,url,jquery) {
        'use strict';

        return Component.extend({
            getInstructions: function() {
                var serviceUrl = url.build('[Module-name]/custom/storeconfig');
                storage.get(serviceUrl).done(
                    function (response) {
                        if (response.success) {
                            return jQuery('.instructions').text(response.value);
                        }
                    }
                ).fail(
                    function (response) {
                        return jQuery('.instructions').text(response.value);
                    }
                );
            }
        });
    }
);

In the above JS file, as you can see we create one function “getInstructions” which calls one controller that returns the system configuration value and that value we can show in specific tag via jquery.

Quick Tip:- Learn to Set Rest API with Example in Magento 1

Step 2: Create Storeconfig.php controller file in the following location

app/code/[Namespace]/[Module]/Controller/Custom/

<?php
namespace [Namespace]\[Module]\Controller\Custom;

class Storeconfig extends \Magento\Framework\App\Action\Action
{
    protected $resultJsonFactory;

    protected $storeManager;

    protected $scopeConfig;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    ) {
        $this->resultJsonFactory = $resultJsonFactory;
        $this->storeManager = $storeManager;
        $this->scopeConfig = $scopeConfig;
        parent::__construct($context);
    }

    /**
     * Execute view action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $response = [];
        try {
            $configValue = $this->scopeConfig->getValue(
                'custom/data/instructions',
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE
            );
            $response = [
                'success' => true,
                'value' => __($configValue)
            ];

        } catch (\Exception $e) {
            $response = [
                'success' => false,
                'value' => __($e->getMessage())
            ];
            $this->messageManager->addError($e->getMessage());
        }
        $resultJson = $this->resultJsonFactory->create();
        return $resultJson->setData($response);
    }
}

As you can see in the above code, we have already created one system configuration field via system.xml and it stores one value or text that we will get it and put in response name array and that response return in JSON.

Step 3: Create custom.html file in the following location

app/code/[Namespace]/[Module]/view/frontend/web/template/payment/

Example HTML:
<p class="instructions" data-bind="html: getInstructions()"></p>

In this file, we will just bind our created function “getInstructions()” in the “P” tag. When that function will call it will get the configuration value and as per our jquery code, it will show the value on the P tag which has “instructions” class.

Thanks for reading this post!

About the author

I’m Magento Certified Developer having quite 5 years of commercial development expertise in Magento as well as in Shopify. I’ve worked primarily with the Magento and Shopify e-commerce platform, managing the complexities concerned in building e-commerce solutions tailored to a client’s specific desires.

Related Posts

25 Responses
  1. You really make it seem so easy with your presentation but I find this matter to be really something
    which I think I would never understand. It seems too complicated and extremely broad for me.
    I’m looking forward for your next post, I’ll try to get
    the hang of it!

  2. Nice post. I used to be checking continuously this blog and I am impressed!
    Extremely helpful info specially the closing
    section 🙂 I care for such info a lot. I was looking for this particular
    info for a long time. Thanks and best of luck.

  3. Excellent post. I was checking constantly this weblog and I’m impressed! Very helpful information specifically the ultimate section 🙂 I deal with such info much. I was looking for this particular info for a very lengthy time. Thanks and best of luck. |

  4. You are so awesome! I do not believe I’ve truly read something like that before. So good to discover somebody with original thoughts on this issue. Seriously.. thank you for starting this up. This web site is something that’s needed on the internet, someone with a little originality!|

  5. I do not even know how I ended up here, but I thought this post was great. I don’t know who you are but certainly you are going to a famous blogger if you aren’t already 😉 Cheers!|

  6. Excellent post. I used to be checking continuously this blog and I am inspired! Very useful info specially the closing section 🙂 I care for such info much. I was seeking this certain info for a very lengthy time. Thank you and good luck. |

  7. We’re a gaggle of volunteers and starting a new scheme in our community. Your website provided us with helpful info to work on. You have done a formidable task and our whole community will probably be grateful to you.|

  8. I’ve been browsing online more than 3 hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. In my opinion, if all web owners and bloggers made good content as you did, the web will be much more useful than ever before.|

  9. Howdy! Someone in my Facebook group shared this site with us so I came to check it out. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Outstanding blog and fantastic design.|

  10. Hello, i think that i saw you visited my site so i came to “return the favor”.I am trying to find
    things to improve my website!I suppose its ok to use
    a few of your ideas!!

  11. An impressive share! I have just forwarded this onto a colleague who has been doing a little research on this. And he in fact ordered me breakfast simply because I discovered it for him… lol. So let me reword this…. Thanks for the meal!! But yeah, thanks for spending time to talk about this topic here on your web site.|

  12. I believe that is among the so much important information for me. And i’m satisfied reading your article. However wanna commentary on few general things, The site taste is ideal, the articles is in point of fact nice : D. Excellent process, cheers|

Leave a Reply