问题
During the checkout process I sometimes want to programmatically remove items from the session's quote. So I tried this code:
$quote = Mage::getSingleton('checkout/session')->getQuote();
$all_quote_items = $quote->getAllItems();
foreach ($all_quote_items as $item) {
$quote->removeItem($item->getId())->save();
}
However, after this loop the list of items in the $quote
object is still the same, i.e. no items have been removed.
Any ideas what I am missing here?
Using Magento 1.4.1.1
回答1:
Try
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item)
{
$itemId = $item->getItemId();
$cartHelper->getCart()->removeItem($itemId)->save();
}
See http://www.magentocommerce.com/boards/viewthread/30113/
回答2:
In Magento 1.7.0.0
version, you can use:
Mage::getSingleton('checkout/cart')->truncate()->save();
回答3:
I do a similar process while looking for items of a certain type, The logic I applied is:
$session= Mage::getSingleton('checkout/session');
$quote = $session->getQuote();
$cart = Mage::getModel('checkout/cart');
$cartItems = $cart->getItems();
foreach ($cartItems as $item)
{
$quote->removeItem($item->getId())->save();
}
Try the above and if that fails I would start dumping the quote objects out before and after this logic is executed to see what differences there are.
回答4:
Try the below code It will work
$product = $observer->getEvent()->getProduct();
$cart = Mage::getSingleton('checkout/cart');
foreach ($cart->getQuote()->getItemsCollection() as $_item) {
if ($_item->getProductId() == $productId) {
$_item->isDeleted(true);
//Mage::getSingleton('core/session')->addNotice('This product cannot be added to shopping cart.');
}
}
来源:https://stackoverflow.com/questions/16057101/how-to-remove-item-from-quote-in-magento