10

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.

4

2 Answers 2

18
+50

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(); 
2
  • 1
    how to update additional options
    – sivakumar
    Apr 17, 2018 at 12:48
  • hi @Amit, How to update taxAmount for the item?, can we set custom tax amount for individual quote item? May 14, 2019 at 14:42
3

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.