0

How i can pass helper data to Knockout JS to show it on my html file. Actually i am working on minicart and i want to show the product Qty as Dropdown and get value from Helperdata.

Any help would be appreciated!

1

1 Answer 1

0

For instance this is your Block function where you get Helper Data:

 public function getConfigData()
   {
       return $this->helper->getHelperPrice();
   }

Then in your .phtml file where you add script tag for JS, do this:

<script type="text/x-magento-init">
    {
        "*": {
            "Vendor_Module/path/to/js_file": {
                "price": <?= /* @noEscape */ $block->getConfigData() ?>
            }
        }
    }
</script>

and finally in your JS file (I've some extra code here):

define([
       'ko',
       'uiComponent',
       'Magento_Customer/js/customer-data',
   ], function (ko, Component, customerData) {
       'use strict';
       var subtotalAmount;
       var maxPrice = config.price; //here we set the helper value;
       var percentage;
       return Component.extend({
           displaySubtotal: ko.observable(true),
           maxprice: '$' + maxPrice.toFixed(2),
           /**
            * @override
            */
           initialize: function () {
               this._super();
               this.cart = customerData.get('cart');
           },
           getTotalCartItems: function () {
               return customerData.get('cart')().summary_count;
           },
          
       });
   });
6
  • That is not passing a value to a KO template, that is declaring a global JS variable which is a terrible idea and would not work if there was more than one price required on a page.
    – Ben Crook
    Commented Nov 4, 2020 at 11:41
  • 1
    Then why don't you answer? Please let us know the right way to do it. Commented Nov 4, 2020 at 11:46
  • I already have here - magento.stackexchange.com/questions/103861/…
    – Ben Crook
    Commented Nov 4, 2020 at 11:58
  • Thanks, that added to my knowledge. Commented Nov 4, 2020 at 12:12
  • I've edited my answer, can you take a look now? @BenCrook Commented Nov 5, 2020 at 4:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.