I created a basic ajax addToCart function in the CartController and it works great. I just want the cart item id in this function.

I run:

$cart->addProduct($product, $params);

Is there no way to output the cart item id from this?


You could hook into two events:

sales_quote_item_save_before and sales_quote_item_save_after.

In the observer for save_before you could check if the item has id null, then set a flag. In save_after check if the flag is set, in that case set the item id in session and retrieve it in the controller and send it to the front end.

  • interesting. Is that going to hinder performance if I call an observer from a controller? – kevando Sep 3 '14 at 17:00
  • This did not work. I tried both events and ran $observer->getItem() with no data coming back. – kevando Sep 3 '14 at 18:32
  • 1
    You have to run $observer->getDataObject() to get the object from pre defined default model prefixed events. – Paras Sood Sep 3 '14 at 18:36

Yes, you can do it. Add an observer and hang its method on event checkout_cart_product_add_after.

Look at method: Mage_Checkout_Model_Cart::addProduct

 * Add product to shopping cart (quote)
 * @param   int|Mage_Catalog_Model_Product $productInfo
 * @param   mixed $requestInfo
 * @return  Mage_Checkout_Model_Cart
public function addProduct($productInfo, $requestInfo=null)
    $product = $this->_getProduct($productInfo);
    $request = $this->_getProductRequest($requestInfo);

    $productId = $product->getId();
    if ($productId) {
        try {
            $result = $this->getQuote()->addProduct($product, $request);
        } catch (Mage_Core_Exception $e) {
            $result = $e->getMessage();
    } else {
        Mage::throwException(Mage::helper('checkout')->__('The product does not exist.'));

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

In observer's method you can get access to quote item and product.

  • So it looks like I could grab the item ID from $result then? – kevando Sep 3 '14 at 16:56
  • Yes, because result will entity of Mage_Sales_Model_Quote_Item. – user13804 Sep 3 '14 at 17:06
  • Ok it makes sense that should have the data, but it's coming back empty. I'm really confused why this is such a challenge. – kevando Sep 3 '14 at 18:32
  • Then I can advice to debug it with help of xdebug - step-by-step. Maybe there is customization or something else. Also, you should try to get something like $quoteItem = $observer->getEvent()->getQuoteItem(), i.e. do not try to get quoteItem from $observer, only through getEvent(). – user13804 Sep 3 '14 at 19:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.