TransWikia.com

Magento 2 get cart items in block class

Magento Asked by Khooshbu Patel on January 20, 2021

I have created block for sidebar.

I have added below code in my block for compare products. It’s working fine

<div class="block widget block-compare">
    <div class="block-title">
    </div>
    {{block class="MagentoFrameworkViewElementTemplate" name="catalog.compare.sidebar" template="Magento_Catalog::product/compare/sidebar.phtml" /}}
</div>

I got output like this: http://prntscr.com/n4jcsj

Now i want to show shopping cart items there above compare. Can anyone help me with this.

I also try with minicart but it is not working as per my requirement. It gives me only link of minicart. I need to show content of minicart. I used this code in block.

<div class="minicart">
    <div> 
        {{block class="MagentoCheckoutBlockCartSidebar" name="mini_cart" template="Magento_Checkout::cart/minicart.phtml"}}
    </div>
</div>

Which gives me output like this : https://prnt.sc/n3h35j

Please help me if anyone has some idea about this.

One Answer

Try Following way...

Create Block file

<?php
namespace VendorModuleBlock;

class ShoppingCart extends MagentoFrameworkViewElementTemplate
{
    public function __construct(
        MagentoFrameworkViewElementTemplateContext $context,
        MagentoCheckoutModelSession $checkoutSession,
        array $data = []
    ) {
        $this->_checkoutSession = $checkoutSession;;
        parent::__construct($context, $data);
    }

    /**
     * Get quote object associated with cart. By default it is current customer session quote
     *
     * @return MagentoQuoteModelQuote
     */
    public function getQuoteData()
    {
        $this->_checkoutSession->getQuote();
        if (!$this->hasData('quote')) {
            $this->setData('quote', $this->_checkoutSession->getQuote());
        }
        return $this->_getData('quote');
    }
}

Call in template(.phtml) file,

<?php
// Get all visible items in cart
$quote = $block->getQuoteData();

foreach($quote->getAllVisibleItems() as $_item) {
    echo 'ID: '.$_item->getProductId().'<br/>';
    echo 'Name: '.$_item->getName().'<br/>';
    echo 'Sku: '.$_item->getSku().'<br/>';
    echo 'Quantity: '.$_item->getQty().'<br/>';
    echo 'Price: '.$_item->getPrice().'<br/>';
    echo 'Product Type: '.$_item->getProductType().'<br/>';
    echo 'Discount: '.$_item->getDiscountAmount();echo "<br/>";
}

Correct answer by Rakesh Donga on January 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP