cancel
Showing results for 
Search instead for 
Did you mean: 

Get Quote Items in Model

Get Quote Items in Model

I am overriding a model file of another module and need current collection of items in cart (at checkout ) in that model to compare some product data How we can achieve that in magento2?

I Tried with the Checkout\Session as

Using this in my model file:

use Magento\Checkout\Model\Session;

Then in my constructor i have initialize the values like:

protected $checkoutSession;

public function __construct(
    Session $checkoutSession
) {
    $this->_checkoutSession = $checkoutSession;
}


and created the new method to get current checkout product like

public function quoteItems()
{
    return  $this->_session->getQuote()->getAllVisibleItems();
}

I have run the di:compile and clear the cache as well

but getting error and blank checkout page.

Any Help will be appreciated.

3 REPLIES 3

Re: Get Quote Items in Model

Why you write $this->_session instead of $this->_ checkoutSession ??


@Shoaib967 wrote:

I am overriding a model file of another module and need current collection of items in cart (at checkout ) in that model to compare some product data How we can achieve that in magento2?

I Tried with the Checkout\Session as

Using this in my model file:

use Magento\Checkout\Model\Session;

Then in my constructor i have initialize the values like:

protected $checkoutSession;

public function __construct(
    Session $checkoutSession
) {
    $this->_checkoutSession = $checkoutSession;
}


and created the new method to get current checkout product like

public function quoteItems()
{
    return  $this->_session->getQuote()->getAllVisibleItems();
}

I have run the di:compile and clear the cache as well

but getting error and blank checkout page.

Any Help will be appreciated.


 

Re: Get Quote Items in Model

public function quoteItems()
{
    return  $this->_checkoutSession->getQuote()->getAllVisibleItems();
}

Re: Get Quote Items in Model

@Shoaib967   for anywhere in Magento 2 modules this code will work

 

 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $cart = $objectManager->get('\Magento\Checkout\Model\Cart');  
        $itemsCollection = $cart->getQuote()->getItemsCollection();
        $itemsVisible = $cart->getQuote()->getAllVisibleItems();
        $items = $cart->getQuote()->getAllItems();
        $cart_items_onload = [];
        foreach($items as $item) {
             echo 'ID: '.$item->getProductId().'<br />';
             echo 'Name: '.$item->getName().'<br />';             
     
        }