I want to delete items from cart while adding new products. I am observing : checkout_cart_add_product_complete
event for this. My code is following:
<checkout_cart_add_product_complete>
<observers>
<secodaryproduct>
<type>singleton</type>
<class>secodaryproduct/observer</class>
<method>checkoutCartAddProductAddComplete</method>
</secodaryproduct>
</observers>
</checkout_cart_add_product_complete>
And for deleting products:
$quote = Mage::getSingleton('checkout/cart');
$quote->removeItem($product['item_id']);
$quote->save();
When i call this code without observer then this works fine and delete required items. But if i use this using observer then items not deleting from cart. I have also put the output in log file and item ids are printing correctly but my items are not deleting from cart. Please help.
When Mage::dispatchEvent('checkout_cart_add_product_complete', ...)
gets invoked in /checkout/cart/add
, the relevant Mage_Catalog_Model_Product
instance gets passed to the event observers. So you should be able to do something like this, which will remove all cart items matching that product ID:
public function checkoutCartAddProductAddComplete(Varien_Event_Observer $observer)
{
/* @var Mage_Catalog_Model_Product $product */
$product = $observer->getProduct();
/* @var Mage_Checkout_Model_Cart $cart */
$cart = Mage::getSingleton('checkout/cart');
$cartItems = $cart->getItems();
/* @var Mage_Sales_Model_Quote_Item $item */
foreach ($cartItems as $item) {
if ($item->getProductId() == $product->getId()) {
$cart->removeItem($item->getId());
}
}
$cart->save();
}