Magento-1.7 Event Observer Quote – Watching Add to Cart Event with Empty Quote Item ID

event-observermagento-1.7quote

I am trying to catch the event that fires once an item is added to the cart. I'm currently watching the following event: checkout_cart_product_add_after

According to magento source this event is fired after everything is done to the Quote. but when i access the cart id and the quote id the values are empty:

$quoteItem = $observer->getQuoteItem();
$quote_item_id = $quoteItem->getItemId();
$cart = Mage::getSingleton('checkout/session');
$quote_id= $cart->getQuoteId();

The above returns empty for both ids when there are no items in the cart, if the cart already has an item the cart id has value but the quote_item_id doesn't.

Notice this has been asked before, but the question was never resolved, and the discussion ended up straying from this issue. I need the quote_item_id.

Best Answer

Don't do this.

Your problem is, that the cart is not yet saved, have a look here:

https://github.com/LokeyCoding/magento-mirror/blob/magento-1.7/app/code/core/Mage/Checkout/controllers/CartController.php#L201-L206

public function addAction()
{
// ...
        $cart->addProduct($product, $params); // <-- you are inside this method
        if (!empty($related)) {
            $cart->addProductsByIds(explode(',', $related));
        }

        $cart->save(); // here is the saving, and therefore after this line,
                       //  quote and items have an id
// ...
        Mage::dispatchEvent('checkout_cart_add_product_complete',
            array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
        );

What you want is to listen on checkout_cart_add_product_complete

If you want to know which items where added this round, just flag them in checkout_cart_product_add_after like $quoteItem->setIsNew() then you can check in checkout_cart_add_product_complete for $quoteItem->getIsNew()