0

For performance reasons I removed the knockout functionality to get the total number of articles in my cart. By using the Magento\Checkout\Helper\Cart helper

On some pages the count of articles in my minicart is always 0. While on other pages (url.com/cart and url.com/contact) the count is showed correct.

Does somebody know what the problem is?

minicart.phtml

<?php
$cartHelper = $this->helper('Magento\Checkout\Helper\Cart');
?>
<span class="MiniCart-items counter-label">
    <span class="u-inlineBlock u-alignMiddle u-marginRxs">
        <?php echo $cartHelper->getItemsCount(); ?>
    </span>
    <span class="u-inlineBlock u-alignMiddle">
        <?php if($cartHelper->getItemsCount() == 1): ?>
            <?php /* @escapeNotVerified */ echo __('Artikel'); ?>
        <?php else: ?>
            <?php /* @escapeNotVerified */ echo __('Artikelen'); ?>
        <?php endif; ?>
    </span>
</span>

1 Answer 1

1

First, you should have use the KO, it does not reduce the performance.

Next, the reason for the uncertain behaviour is Magento full page cache. I hope if you disable the full page cache it will work good, but that is not the solution. So, first let's find out why it is showing correct value in contact page.

If you go to the \Magento\Contact\Block\ContactForm block class, and check the constructor, you can see the code below -

    public function __construct(Template\Context $context, array $data = [])
    {
        parent::__construct($context, $data);
        $this->_isScopePrivate = true;
    }

The block scope is private here - $this->_isScopePrivate = true; So basically this particular block should be out of full page cache control. But I guess magento exclude the whole page elements from cache (which might be a M2 bug, i am not sure either). You can see the same thing for any account or cart pages.

Now to make your code works, you need override Magento\Checkout\Block\Cart\Sidebar to make it's scope private or you need to use your own block/xml/phtml methodology to show the content where you can make your custom block scope private.

But I am worried that, this may lead you to exclude all pages from full page cache as mini cart is common to all pages.

Using KO is the best option, as it uses delay rendering that should not affect your performance.

Your Answer

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

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