Remove items from cart when adding new products in magento

I want to remove items from the cart when new products are added. I am watching: an checkout_cart_add_product_complete

event for this. My code looks like this:

<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 to remove 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 removes the required items. But if I use this using an observer, then the items are not removed from the trash. I also put the output in a log file and item ids are printed correctly, but my items are not removed from the trash. Please, help.

+3


source to share


1 answer


When Mage::dispatchEvent('checkout_cart_add_product_complete', ...)

called in /checkout/cart/add

, the corresponding instance Mage_Catalog_Model_Product

is passed to event observers. So you should be able to do something like this, which will remove all cart items that match 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();
}

      

0


source







All Articles