从购物车中删除给定产品ID的商品

时间:2013-11-22 06:13:58

标签: magento-1.7 magento-1.4 magento-1.5 magento-1.6

我是magento的新手我试图在调用此事件时删除购物车中的商品checkout_cart_product_add_after当我尝试此代码时,没有什么可以做。任何身体帮助我。感谢。

$myProductId=20;
$product = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($myProductId);
$quote =  Mage::getSingleton('checkout/session')->getQuote();
$cartItems = $quote->getItemByProduct($product);
if ($cartItems) {  $quote->removeItem($cartItems->getId())->save();}

4 个答案:

答案 0 :(得分:6)

ItemId(购物车中商品的ID)与其代表的产品的ProductId不同。尝试迭代购物车中的商品,直到找到包含要删除的ProductId的商品:

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

请按照上述说明进行尝试。

答案 1 :(得分:1)

下面的代码工作对我来说你可以尝试这个你可以使用ajax或post方法调用这个函数把这个函数放在你的控制器中并调用它。传递客户ID并将其产品发送给它

public function removeCartAction()
{
    $productId = trim($_POST['productId']);
    $customer  = trim($_POST['requesterId']);
    if ($customer) {
        $storeId = Mage::app()->getWebsite(true)->getDefaultGroup()->getDefaultStoreId();
        // get quote table cart detail of all customer added 
        $quote = Mage::getModel('sales/quote')->setStoreId($storeId)->loadByCustomer($customer);        
        if ($quote) {
            $collection = $quote->getItemsCollection(false);
            if ($collection->count() > 0) {
                foreach( $collection as $item ) {
                    if ($item && $item->getId()) {
                        $quote->removeItem($item->getId());
                        $quote->collectTotals()->save();
                    }
                }
            }
        }
    }       
}

答案 2 :(得分:0)

要从购物车(报价单)中按特定item_id删除商品,您可以使用:

         $cart = Mage::getModel('checkout/session')->getQuote();

         $cartHelper = Mage::helper('checkout/cart');
         $items = $cart->getAllVisibleItems();
         foreach($items as $item):
         if($item->getItemId() == $id):
               $itemId = $item->getItemId();
               $cartHelper->getCart()->removeItem($itemId)->save();
               break;
         endif;
         endforeach;

答案 3 :(得分:0)

执行此操作即可获得输出

$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.');
        }
    }