Question

I have been developing a module for Magento2 Checkout that fills some information, not important what, this data resides in Magento's db, and I am able to access it via Magento database access layer.

My question is, how do I get this retrieve this data and use it in a Knockoutjs UI Component in Checkout?

Was it helpful?

Solution

I was able to get this working by implementing a ConfigProvider via implementing ConfigProviderInterface.

<?php

namespace My\Plugin\Model;

class MyPluginConfigProvider implements ConfigProviderInterface
{
    protected $scopeConfig;

    public function __construct(
        ScopeConfigInterface $scopeConfig
    ) {
        $this->scopeConfig = $scopeConfig;
    }

    public function getConfig()
    {
        $config = [
            'store_address' => [
                'name' => $this->scopeConfig->getValue('general/store_information/name'),
                'city' => $this->scopeConfig->getValue('shipping/origin/city'),
                (...)
            ]
        ];
        return $config;
    }
}

Added it to app/code/My/Plugin/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">
    <type name="Magento\Checkout\Model\CompositeConfigProvider">
        <arguments>
            <argument name="configProviders" xsi:type="array">
                <item name="instore_config_provider" xsi:type="object">Premiergroup\InStoreShipping\Model\InStoreConfigProvider</item>
            </argument>
        </arguments>
    </type>
</config>

And then, finally, called it from within my ko uiComponent:

define(
[
    'jquery',
    'ko',
    'uiComponent'
],
function (
    $,
    ko,
    Component
) {
    'use strict';
    return Component.extend({
    (...)

    functionToBind: function () {
        var storeName = window.checkoutConfig.store_address.store_name;
        // do something with the storeName

I hope someone else finds this helpful and I can't find any documentation on this!

OTHER TIPS

In the phtml file where you get the Value from db write below code:

.phtml file code:

<script>
    window.myData = "<?php echo $datafromdb ?>";
</script>

in Knockout js you can access this data like:

define(
    [
        //your model
    ],
    function (url) {
        'use strict';

        return {
            mydata: window.myData,
        };
    }
);
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top