Magento – Magento2 : How to display custom values in checkout page

knockoutknockoutjsmagento2

I am working on checkout page, I have pass some array values to checkout config provider.

How to get those values in knockout JS and display by knockout html.

Want to display all applied codes in checkout payment step.

I have passed values to config provider by below code

public function getConfig()
    {
        return $this->getAppliedGiftCards();
    }

    public function getAppliedGiftCards()
    {
        $quoteId = $this->checkoutSession->getQuote()->getId();
        $giftcardCodes = $this->quoteFactory->getGiftCardCollection($quoteId);
        $config = [];
        foreach ($giftcardCodes as $giftcardCode){
            $config['payment']['applied_giftcard'][$giftcardCode->getCode()] = $giftcardCode->getCode();
        }
        return $config;
    }

Get values in Js by below code

var configValues = window.checkoutConfig.payment;
var applied_giftcard = ko.observable(configValues.applied_giftcard);

How to render passed config array value to knockout template.

Best Answer

You want to add window.checkoutConfig then you need to create a plugin on Magento\Checkout\Model\DefaultConfigProvider.

Create after method on getConfig() afterGetConfig and add pass you array as json value.

Create di.xml at app/code/{Vendor}/{Module}/etc.

<?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\DefaultConfigProvider">
        <plugin name="add_new_variable_checkout_config" type="{VendorName}{ModuleName}\Plugin\DefaultConfigProviderPlugin" sortOrder="1" />
    </type>
</config>

Plugin class

namespace {VendorName}\{ModuleName}\Plugin;

class DefaultConfigProviderPlugin
{

 
    public function afterGetConfig(
        \Magento\Checkout\Model\DefaultConfigProvider $subject,
    $output     
    ) {
        $output['my_custom_data'] = json_encode(array('name'=> 'john', 'age' => '10'));
    return $output;
    }
 
} 

Now, you want to render this data to payment section then ,Please copy

vendor/magento/module-checkout/view/frontend/web/js/view/payment.js

to your theme level

app/design/frontend/{Venoder}/{Themename}/Magento_Checkout/web/js/view/payment.js

OR Rewrite module-checkout/view/frontend/web/js/view/payment.js

and new function getmyCustomdata name for getting value from the config value

    ......
    getmyCustomdata: function () {
        return window.checkoutConfig.my_custom_data;
    }  

Now, you have to print getmyCustomdata value to knockjs HTML template vendor/magento/module-checkout/view/frontend/web/template/payment.html

So, copy this file to to your theme level.

app/design/frontend/{Venoder}/{Themename}/Magento_Checkout/web/template/payment.html

At this payment.html bind data using <span data-bind="text: getmyCustomdata()"></span>

Related Topic