Magento 2 – How to Get Quantity and Subtotal for All Products Added to Cart

cartmagento2mini-cartproduct

I tired to get the total qty of products added to cart and also the subtotal in a custom phtml on product page.

For that i use this code but without success:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart'); 
$totalQuantity = $cart->getQuote()->getItemsCount();
$grandTotal = $cart->getQuote()->getGrandTotal();

and:

$helper = $this->helper('\Magento\Checkout\Helper\Cart');
echo $helper->getItemsCount();

Is there another solution?

Best Answer

This is how i solve this problem:

in my block:

use Magento\Checkout\Model\Cart as CustomerCart;

protected $cart;

public function __construct(

        CustomerCart $cart
        array $data = array()

    ) {

        $this->cart = $cart;

        parent::__construct($context);
    }



public function getProductQtyCustom(){

        $counting = $this->cart->getSummaryQty();
        return $counting;
    }


     public function getSubtotalHtmlCustom()
    {
        $totals = $this->cart->getQuote()->getTotals();

        $subtotal = $totals['subtotal']['value'];
        return $subtotal;
    }

after this in my phtml i used this funcitons like this $block->function();

Related Topic