In magento 2.2.5, I tried to get the quote item using below codes. But it is not working.
-
Can you please upload your code here? – Emipro Technologies Pvt. Ltd. Nov 28 '18 at 6:05
-
when and where you want to get quote item? – Amit Bera♦ Nov 28 '18 at 7:36
Try below code in your block file:
protected $cart;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Checkout\Model\Cart $cart,
\Psr\Log\LoggerInterface $logger,
array $data = []
)
{
$this->cart = $cart;
$this->_logger = $logger;
parent::__construct($context, $data);
}
public function getQuoteItems()
{
$items = null;
try{
$items = $this->cart->getQuote()->getAllVisibleItems();
}catch(\Exception $e){
$this->_logger->debug($e->getMessage());
}
return $items;
}
To check if quote items are being collected properly, please check by displaying items sku using array iteration as given below:
foreach($items as $item)
{
echo $item->getSku();
}
die;
Check and let me know if it helps.
The link you mention in your question is overloading Magento cart controller (\Magento\Checkout\Controller\Index\Index). For me the links code is working fine but if you are not overloading Magento cart controller then you can change your code as follows
step 1 : please comment out controller preference in your di.xml file.
your updated di.xml may look as below
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<!--<preference for="Magento\Checkout\Controller\Index\Index" type="Company\MyModule\Controller\Index\Index" />-->
</config>
step 2 : Replaces your Controller/Index/Index.php code with below code (we assumed your are using a custom extension name Company_MyModule )
File Index.php
<?php
namespace Company\MyModule\Controller\Index;
use Magento\Framework\Controller\ResultFactory;
class Index extends \Magento\Framework\App\Action\Action
{
protected $checkoutSession;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Checkout\Model\Session $checkoutSession
) {
$this->storeManager = $storeManager;
$this->checkoutSession = $checkoutSession;
parent::__construct($context);
}
public function execute()
{
$quoteId = $this->checkoutSession->getQuote()->getId();
$quoteItems = $this->checkoutSession->getQuote()->getItemsCollection();
if(count($quoteItems)){
foreach($quoteItems as $item){
print_r($item->getData());
//insert your custom code here
//TODO
}
}
parent::__construct($context);
}
}