Question

I am trying to update quote item in magento2. But every time i am saving the item its creating a new item with the same quote id rather than updating it. Here is my code

    public function __construct(
            \Magento\Quote\Model\QuoteRepository $quoteRepo
        ){
            $this->_quoteRepo = $quoteRepo;
        }

public function updateItem(){
    $quote = $this->_quoteRepo->get('id here');
    foreach($quote->getAllVisibleItems() as $itemq){
    $itemq->setQty(5);
    $itemq->setPrice(20);
    $itemq->save();
    }
 }

But every time its saving an item.. a new item is getting generated. Dont know why. Also I couldn't find any class which explicitly load qoute item in magento2. Help will be appreciated.

In this question https://magento.stackexchange.com/questions/139298/how-to-save-quote-items-in-magento-2 they are setting the whole product... not trying to update it. When you set a product a new quote item will surely generate. But why its doing the same in case of updation.

Was it helpful?

Solution

I am not sure about my below solution:

  • May be you need to load Quote item object by item id
  • As you want set price then using setPrice() you cannot set your desire price for that cart item
$item = $quote->getItemById($item->getId());
if (!$item) {
  continue;
}
$item->setQty((double) $qty);
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
$item->getProduct()->setIsSuperMode(true);
$item->save(); 

OTHER TIPS

The functionality you are asking about is already done in Magento\Checkout\Controller\Cart\UpdatePost which is executed when we update cart on cart page of magento. It runs updateItems() function of Magento\Checkout\Model\Cart to update items in quote_item table . It take parameter in the form of array $data ['item id of product']['attribute you want to update'].

So , you can call updateItems() on cart model object and pass the data accordingly to update items.Also if you are not getting item id you can get it like $this->cart->getQuote()->getAllItems() and then call getItemId() on each item.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top