Magento – ItemID is not available at checkout_cart_product_add_after

cart

I am basically trying to implement the scenario where certain special products can only be brought once in customer's lifetime. So need to make sure that if they are added again after being purchased in past, they are swapped with another regular product.

All this is working on checkout_cart_product_add_after except the problem that the product which has been just added doesn't have Item ID assigned to it yet. My understanding is that the item ID hasn't been assigned to it since I am in middle of the saving process.

This is what it looks like inside the observer:

enter image description here

How can I remove an item at this point of execution without itemID being available? I studied Cart & Quote classes in Core and I don't see any way of removing item without knowing its ItemID since its basically just an element of array.

Should I be using another event to do this where this is available? My only concern is that I need to implement the whole swapping in place, not just removed the just added item in cart. So need a combination that works for both (removing the just added product + add more as its replacement).

Any pointers?

Best Answer

In short, the product has been added to the cart at this point, If you're trying to swap in-place and prevent the cart add I suggest you call within your current observer's cart item setQty(0) which will trigger the removal.

In-depth:

The only thing not completed before the call to checkout_cart_product_add_after is to add the product id to the checkout's session. If you'd like to investigate this method further, check out Mage_Checkout_Model_Cart::addProduct.

So, the dispatch gives us two things in addProduct -

Mage::dispatchEvent('checkout_cart_product_add_after', array('quote_item' => $result, 'product' => $product));

We have access to the quote item itself, meaning, that it is already on the quote; so it needs to have an ID. Handling it prior to the add seems like the reasonable thing to do here, though, one could conceive that calling removeItem would also probably work:

$cartItem = $observer->getEvent()->getQuoteItem();
$cartItem->getQuote()->removeItem($cartItem->getId())->save();

Though, you said you can't do getId, which I find strange. If that's the case, use the setQty I describe above.