Magento: update the basket number programmatically

I am creating a magento extension. In which I want to programmatically update the number of items in the cart. I use the following code to display items in a recycle bin.

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

I want to update the cart quantity for a specific product. I know this 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 do not like this method, because it will go through each product in order to update the quantity of one product. I wonder if there is a way to update the quantity in a single line of i: e without using for a loop.

+5
source share
2 answers

Do you have product_id and not item_id right?

If in this case it is not possible to obtain the product identifier without completing all the elements.

Mage_Sales_Model_Quote::getItemByProduct($product);, , .

:

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

:

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

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

, ...

, - , , .

,

+12

, . . .

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";
}
+2

All Articles