2013-03-01 52 views
5

我正在創建一個magento擴展程序。其中我想以編程方式更新購物車中的商品數量。我正在使用下面的代碼來顯示購物車中的物品。Magento:以編程方式更新購物車的數量

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

我想要的是更新特定產品的購物車數量。我知道這是可以做到這樣的

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

但我不喜歡這種方法,因爲它會經歷每一個產品更新單個product.I奇蹟的數量是否有更新的方式數量在一行i:e中,不用於循環。

+0

你正在使用什麼事件? – 2013-11-26 10:06:53

+0

檢查此:http://www.onlinecode.org/magento-update-cart-quantity/ – 2017-03-16 05:51:50

回答

12

你有product_id,而不是item_id的權利?

如果是這種情況,不可能在沒有執行整個項目的情況下獲取產品ID。

看看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()) 

檢查數量不已經很好...

請注意,它是未經測試的代碼,以及某種反射來幫助您找到解決方案,我沒有爲您完成這項工作。

親切的問候,

+0

如果我有項目編號,那麼我該如何做到這一點? – 2013-03-02 06:09:44

+0

如果您有item_id,請刪除2條第一行,並將其替換爲$ item = Mage :: getModel('sales/quote_item') - > load($ item_id);和$ pid = $ item-> getProductId(); – dagfr 2013-03-02 13:55:42

+1

我不得不這樣修改才能使它工作:$ quote-> updateItem($ itemId,array('qty'=> $ qty)); – Mark1inLA 2014-07-07 20:32:12

2

我相信它會工作。嘗試這個。這是節省我的時間。

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