简体   繁体   中英

Magento: Update cart quantity programmatically

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.

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,

I am sure it will work. Try this. It's save's my time.

public function updateCartAction(){
    $item_id = $this->getRequest()->getParam('item_id');
    $qty = $this->getRequest()->getParam('qty');

    $quote = Mage::getSingleton('checkout/session')->getQuote();
    $quote->updateItem($item_id, array( 'qty' => $qty));
    $quote->save();
    echo "Sssssss";
}

another solution

  $quote = Mage::getModel('sales/quote')->setStoreId($storeId)->load($cartid);
     $cartItems = $quote->getAllItems();
        foreach ($cartItems as $item) {

         if($cartiemid==$item->getId()){
             $item->setQty($qty);
             $item->save(); // you need to save the item after qty update
         }

        }
    $quote->save();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM