This is triggered on the checkout_cart_add_product_complete
event.
Firstly the code in the if($itemCount > 1)
statement works absolutely fine and as expected (it removes the last item/item just added to cart). However the code in the else statement does not.
The item is a simple product.
The else statement is triggered when the customer has an empty cart, and is adding a first product to it which happens to be an item that has failed a check. So it needs to be removed from the cart, leaving them with an empty cart (and some error messages eventually).
However, the else statement does not want to delete that first and only item from the cart. You will be able to see all of the other methods I have tried as I have just commented them out.
I use XDebug and have been stepping through the code, so I can assure you that it makes it into the statement and executes $cart->removeItem($itemId)->save();
- However no errors are shown in logs or from the catch.
I'm at a loss with this, tried so many things but all to no avail. Please someone shed some light & make what I want to achieve possible! Thanks.
Code:
public function removeItem(Varien_Event_Observer $observer)
{
$event = $observer->getEvent();
$productId = $_SESSION['prescription']['product_id'];
$result = $_SESSION['prescription']['result'];
if($result == 0)
{
$cart = Mage::helper('checkout/cart')->getCart();
$items = $cart->getItems();
$itemCount = count($items);
if($itemCount > 1)
{
$i = 0;
foreach($items as $item)
{
$i++;
if($i == $itemCount)
{
if($item->getProduct()->getId() == $productId)
{
$itemId = $item->getItemId();
$cart->removeItem($itemId)->save();
}
}
}
}
else
{
foreach($items as $item)
{
if($item->getProduct()->getId() == $productId)
{
try{
$itemId = $item->getItemId();
$cart->removeItem($itemId)->save();
//Mage::getSingleton('checkout/cart')->truncate()->save();
//$quote = Mage::getSingleton('checkout/session')->getQuote();
//$quote->removeItem($itemId)->save();
}catch (Exception $e)
{
Mage::log('Failed to remove item from cart'.$e.'.');
}
}
}
}
}
}