Magento: Update cart quantity programmatically

Nirmal Ram picture Nirmal Ram · Mar 1, 2013 · Viewed 31k times · Source

I am creating a magento extension. In which I want to update the item quantity in cart programmatically. I am using the following code to display the items in cart.

$quote = Mage::getSingleton('checkout/session')->getQuote();
$cartItems = $quote->getAllVisibleItems();
foreach ($cartItems as $item) {
  //Do something
}

What i want is to update the quantity on cart for a specific product. I know it can be done like this

$pid=15;
$quote = Mage::getSingleton('checkout/session')->getQuote();
$cartItems = $quote->getAllVisibleItems();
foreach ($cartItems as $item) {
if($pid==$item->getId())
$item->setQty($qty);
}

But I don't like this method as it would go through each and every product to update the quantity of a single product. I wonder if there is a way to update the quantity in one line i:e without using for loop.

Answer

dagfr picture dagfr · Mar 1, 2013

You have the product_id, not the item_id right ?

If it's the case it's impossible to get the product id without performing the whole items.

Look at Mage_Sales_Model_Quote::getItemByProduct($product); you'll see it performs the whole catalog.

Basically I'll do it like this :

//get Product 
$product = Mage::getModel('catalog/product')->load($pid);
//get Item
$item = $quote->getItemByProduct($product);

$quote->getCart()->updateItem(array($item->getId()=>array('qty'=>$qty)));
$quote->getCart()->save();

You should optimise this with some quick tricks :

$quote->hasProductId($pid) to check if product is in the cart

and

($qty!=$item->getQty())

to check if quantity is not already good...

Please note that it is untested code, and some kind of reflexions to help you find the solution, I didn't do the job for you.

Kind Regards,