1
votes

I am creating a new cart addAction() in magento's checkout/controllers/cartController.php. My need is, Whenever a product is added to cart, all existing products in cart should be cleared except currently added one. That is,

If Nokia 3220 is added to an empty cart, It should be placed as an item.

And Later if Nokia N72 is added, Nokia 3220(ie the previous item) should be cleared from cart and Nokia N72 should be placed and so on.

I override the CartController.php and added the code to begining of addAction() in CartController.php,

$checkout_my_cart = Mage::getSingleton('checkout/cart'); $current_items = $checkout_my_cart->getItems(); foreach ($current_items as $item) { $itemId = $item->getItemId(); $checkout_my_cart->removeItem($itemId)->save(); }

But It clears the entire cart when I add a new item to replace existing one! I think It should not do it since I added the code in the begining of Addaction(). I tried by defining the above code as a function and calling it with addAction(). But story seems to be the same.

Any help will be appreciated.

Please Help.

2
I got the solution. Just truncate the cart before adding new item. I was not aware of it....... Mage::getSingleton('checkout/cart')->truncate();Vishnu R

2 Answers

3
votes

You should consider using observer rather then overriding controller. If you look at the addItem method within Mage_Sales_Model_Quote you will find that event sales_quote_add_item.

You can observe it, fetch the quote_item (argument to event) and delete items other then this one (was typing by hand so please double check for errors):

public function observeAddItem($observer) 
{
  $item = $observer->getEvent()->getQuoteItem();
  $cart = Mage::getSingleton('checkout/cart');
  foreach ($cart->getQuote()->getItemsCollection() as $_item) {
    if($_item->getId() != $item->getId()) {
      $_item->isDeleted(true);
    }
  }
}

Overriding classes (especially controllers) should be your last resort.

More info on how to observe event can be found on magento wiki:

http://www.magentocommerce.com/wiki/5_-_modules_and_development/0_-_module_development_in_magento/customizing_magento_using_event-observer_method

0
votes

Hi please check below code:

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