Magento - 从购物车中删除一个数量

时间:2012-11-15 12:57:19

标签: magento cart

我试图从我的购物车中删除一个数量而不是全部,但无济于事。

有人可以帮忙吗?

这是我到目前为止的代码......

require_once 'app/Mage.php';
Mage::app("default");
Mage::getSingleton("core/session", array("name" => "frontend"));
$session = Mage::getSingleton("customer/session");

$yourProId = $_POST['prodID'];
$qty = 1;

foreach (Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection() as $item) {
    if ($yourProId == $item->getProductId()) {
        Mage::getSingleton('checkout/cart')->removeItem($item->getId())->save();
    }
}

更新:感谢R.S.以下代码正常运行。为此!

$yourProId = $_POST['prodID']; 
$qty=1; 

$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item) {
if ($item->getProduct()->getId() == $yourProId) {
    $qty = $item->getQty() - 1; // check if greater then 0 or set it to what you want
    if($qty == 0) {
        Mage::getSingleton('checkout/cart')->removeItem($item->getId());    
    } else {
            $item->setQty($qty);
        }
        $cartHelper->getCart()->save();
        break;
    }
}

2 个答案:

答案 0 :(得分:4)

尝试

$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item) {
    if ($item->getProduct()->getId() == $yourProId) {
        if( $item->getQty() == 1 ){
            $cartHelper->getCart()->removeItem($item->getItemId())->save();
        }
        else if($item->getQty() > 1){
            $item->setQty($item->getQty() - 1)
            $cartHelper->getCart()->save();
        }
        break;
    }
}

看一下@ /app/code/core/Mage/Checkout/controllers/CartController.php

请参阅http://www.magentocommerce.com/boards/viewthread/30113/

答案 1 :(得分:0)

您可以使用$ quoteItem-> setData('qty',$ avl_qty)更改或删除数量; 请参阅代码以获取更多帮助。

$quoteItem = $observer->getEvent()->getQuoteItem();
$avl_qty = 1;
if ($avl_qty == '0') {
  $quoteItem->getQuote()->removeItem($quoteItem->getItemId());
  throw new LocalizedException(__("This product is currently out of stock."));                    
} 
elseif ($order_qty > $avl_qty) {                   
  $quoteItem->setData('qty', $avl_qty);
  $this->_cart->save();
  $this->messageManager->addNoticeMessage('Sorry we have only '.$avl_qty.' qty of this product available');                    
} 
else {                   
}