Tuesday, May 3, 2016

Get shopping cart details in Magento2

Leave a Comment

I know in Magento 1 you can get the shopping cart details on any page with:

$cart = Mage::getModel('checkout/cart')->getQuote(); foreach ($cart->getAllItems() as $item) {     $productId = $item->getProduct()->getId();     $productPrice = $item->getProduct()->getPrice(); } 

How do I do the same thing in Magento 2?

2 Answers

Answers 1

Use the \Magento\Checkout\Model\Session.php::getQuote() method:

magento/magento2/blob/958164/app/code/Magento/Checkout/Model/Session.php#L200-L207

/**  * Get checkout quote instance by current session  *  * @return Quote  * @SuppressWarnings(PHPMD.CyclomaticComplexity)  * @SuppressWarnings(PHPMD.NPathComplexity)  */ public function getQuote() 

Answers 2

Usage examples 1. \Magento\Checkout\Block\Cart\AbstractCart::getQuote() github.com magento/magento2/blob/958164/app/code/Magento/Checkout/Block/Cart/AbstractCart.php#L101-L112

/**  * Get active quote  *  * @return Quote  */ public function getQuote() {     if (null === $this->_quote) {         $this->_quote = $this->_checkoutSession->getQuote();     }     return $this->_quote; } 
  1. \Magento\Checkout\Block\Cart\Totals::getQuote() github.com magento/magento2/blob/958164/app/code/Magento/Checkout/Block/Cart/Totals.php#L190-L205

    /**

    • Get active or custom quote *
    • @return \Magento\Quote\Model\Quote */ public function getQuote() { if ($this->getCustomQuote()) { return $this->getCustomQuote(); }

      if (null === $this->_quote) { $this->_quote = $this->_checkoutSession->getQuote(); } return $this->_quote; }

  2. \Magento\Checkout\Helper\Cart::getQuote() github.com magento/magento2/blob/958164/app/code/Magento/Checkout/Helper/Cart.php#L146-L155

    /**

    • Retrieve current quote instance *
    • @return \Magento\Quote\Model\Quote
    • @codeCoverageIgnore */ public function getQuote() { return $this->_checkoutSession->getQuote(); }
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment