9

I'm trying to get the cart quote total in minicart.phtml, but I'm having no luck. I'm injecting Magento\Checkout\Model\Cart.

Here's my code:

$this->cart = $cart;
$cartQuote= $this->cart->getQuote()->getData();
echo $cartQuote['base_grand_total'];

After I run that code the minicart breaks and disappears totally from the frontend.

Thanks!

  • Can you share more information? – Sohel Rana Jun 16 '16 at 18:32
  • Hei. Seems not to work after update to 2.1 it only returns data when in cart/checkout page, other pages are returning 0 values. – Frii Zuurikas Aug 29 '16 at 11:57
16

You have to just keep below line in your minicart.phtml file to get updated subtotal ,

This Below line is workig for all cases if cache is enable its working fine,

<span data-bind="html: getCartParam('subtotal')"></span> 

For getting value of grandtotal,shipping rate,

You can get GrandTotal, subtotal and shipping rate for current quote using below code in minicart.phtml file, But when cache is enable at that time not update price when you add new product using below method.

<?php
    $quote = $block->getTotalsCache();
    $getSubTotal = $quote['subtotal']->getData('value');
    $getGrandTotal = $quote['grand_total']->getData('value');
    $getShippingRate = $quote['shipping']->getData('value');

        $finalSubTotal = $this->helper('Magento\Framework\Pricing\Helper\Data')->currency(number_format($getSubTotal,2),true,false);
        $finalShippingTotal = $this->helper('Magento\Framework\Pricing\Helper\Data')->currency(number_format($getShippingRate,2),true,false);
        $finalGrandTotal = $this->helper('Magento\Framework\Pricing\Helper\Data')->currency(number_format($getGrandTotal,2),true,false);
?>
  • It worked perfectly on my localhost xamp on ubuntu, but $quote = $block->getTotalsCache(); not working on test server linux fedora – Kumar A. Sep 14 '16 at 9:28
  • Its already working on linux server, i think you have some conflict or some other error. – Rakesh Jesadiya Sep 14 '16 at 9:29
  • I got more involved and find $block->getTotalsCache(); works only when cache is disabled. Have you checked this with Cache Enabled? Mine is Magento2.1.0 – Kumar A. Sep 14 '16 at 10:44
  • 1
    How to get discount amount like this? – Deeban Babu Sep 28 '16 at 12:48
  • @KumarAbhinav, please keep <span data-bind="html: getCartParam('subtotal')"></span> to get dynamic price after cache enable. – Rakesh Jesadiya Dec 7 '16 at 12:14
0

Define a block in your layout in which class marked as "Magento\Checkout\Block\Cart\Totals"

<block class="Magento\Checkout\Block\Cart\Totals" name="quote.print.totals" as="quote.print.totals" after="checkout.cart" 
            template="MyNamespace_PrintCart::totals.phtml"/>

Then in .phtml you can have below code

<?php 
$totals = $block->getTotals() ;
?>
<table class="data table totals">
    <tbody>
        <?php foreach($totals as $key => $total) :?>
            <?php if(!empty($total->getValue())) :?>
                <tr>
                    <td><?= $total->getTitle()->getText() ?></th>
                    <td>
                        <span class="price"><?= $this->helper('Magento\Framework\Pricing\Helper\Data')->currency(number_format($total->getValue(),2),true,false) ?></span>                    
                    </td>
                </tr>
            <?php endif ?>
        <?php endforeach ?>
    </tbody>
    </table>

Expected Output

enter image description here

5

This above code will works on the page load, but will not work with magento2 ajax add to cart as it uses Knockout JS now.

For that you should use -

  1. Override the magento class "\Magento\Checkout\CustomerData\Cart" in your module and extend method "getSectionData"
    public function getSectionData()
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of Object Manager
        $priceHelper = $objectManager->create('Magento\Framework\Pricing\Helper\Data'); // Instance of Pricing Helper

        $totals = $this->getQuote()->getTotals();
        return [
            'summary_count' => $this->getSummaryCount(),
            'subtotal' => isset($totals['subtotal'])
                ? $this->checkoutHelper->formatPrice($totals['subtotal']->getValue())
                : 0,
            'subtotal_value' => isset($totals['subtotal'])
                ? $priceHelper->currency($totals['subtotal']->getValue(),true,false)
                : '',
            'possible_onepage_checkout' => $this->isPossibleOnepageCheckout(),
            'items' => $this->getRecentItems(),
            'extra_actions' => $this->layout->createBlock('Magento\Catalog\Block\ShortcutButtons')->toHtml(),
            'isGuestCheckoutAllowed' => $this->isGuestCheckoutAllowed(),
        ];
    }

Here I have added a new cart param "subtotal_value" as the "subtotal" will return the price container span and it will display as TEXT using KO. Here you have to use "Object Manager Instance" directly, as you wont be able to inject dependencies to the "__construct".

NOTE, there are few exception where we might need to use "Object Manager Instance" directly. In our case it is backward compatibility of constructor.
ObjectManager Exception

  1. Next, copy magento default theme "/cart/minicart.phtml" to your theme and add the KO codes.

    ko text: getCartParam('subtotal_value')

7

We had a similar question from a client. where he wanted to show "[quantity] item [subtotal]" in a styled cart block instead of the default cart icon in the minicart.

We found this question here but didn't like the answer where we needed to extend the \Magento\Checkout\CustomerData\Cart class just to render some html correctly

this is the code how we fixed it in the template:

<span class="counter-label">
    <!-- ko if: getCartParam('summary_count') == 1 -->
        <!-- ko text: getCartParam('summary_count') --><!-- /ko -->
        <!-- ko i18n: 'item' --><!-- /ko -->
        <span data-bind="html: getCartParam('subtotal')"></span>
    <!-- /ko -->
    <!-- ko if: getCartParam('summary_count') != 1 -->
        <!-- ko text: getCartParam('summary_count') --><!-- /ko -->
        <!-- ko i18n: 'items' --><!-- /ko -->
        <span data-bind="html: getCartParam('subtotal')"></span>
    <!-- /ko -->
</span>

It seems like you can also use the standard knockout.js data binding and don't persé need to use the crazy magento 2 knockout comment method. this solved the problem where rendering the getCartParam('subtotal') with the html method where it would normally print the subtotal incorrectly due to the <span ="price"></span> tag

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.