0

I'm trying to get total number of cart items in my custom_header.phmtl. But I'm unbale to get the result.

I've tried using KnockoutJS. I added minicart UI component to my block, which allowed me to display the summary_count variable.

My XML looked something like this:

        <block class="Magento\Framework\View\Element\Template" name="custom_header" as="custom_header" template="Magento_Theme::html/custom_header.phtml" before="-">
            <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="components" xsi:type="array">
                        <item name="my-item-count" xsi:type="array">
                            <item name="component" xsi:type="string">Magento_Checkout/js/view/minicart</item>
                        </item>
                    </item>
                </argument>
            </arguments>
        </block>

And in my custom_header.phtml file I added these two codes,

so I can get summary count:

  <span id="HeaderCartBadge" data-bind="scope:'my-item-count'">
      <!-- ko text: getCartParam('summary_count') --><!-- /ko -->
  </span>

  <script type="text/x-magento-init">
      {
          "#HeaderCartBadge": {
              "Magento_Ui/js/core/app": <?php /* @escapeNotVerified */ echo $block->getJsLayout();?>
          }
      }
  </script>

But I'm getting this error:

[ERROR] Failed to load the "Magento_Checkout/js/view/minicart" component.

Do I need to extend minicart.js file or something else. Please help me out as I'm new in it.

Thanks.

1

You can make your block non-cacheable by adding cacheable="false" attribute to it in the layout xml:

<block class="Magento\Framework\View\Element\Template" name="custom_header" as="custom_header" template="Magento_Theme::html/custom_header.phtml" before="-" cacheable="false">

get the item count from javascript localStorage. Here's a quick and easy way to do it:

<span data-bind="text: JSON.parse(window.localStorage.getItem('mage-cache-storage')).cart.summary_count"></span>

Ref - Click

| improve this answer | |
  • Thanks. But I want to show item count using KnockoutJs. – Chirag Patel Mar 11 at 3:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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