Nirmal Ram Nirmal Ram - 1 year ago 1021
PHP Question

Magento: Update cart quantity programatically

I am creating a magento extension. In which i want to update the item quantity in cart programatically. 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

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

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 Source

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);


You should optimise this with some quick tricks :

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



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,

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download