Magento – Which Checkout event should I use to execute code after product is added to cart

event-observerproduct

I'm working on Magento CE 1.9 and I would like to execute the following code after the customer adds a product to cart:

<?php
$id = '226'; // Replace id with your product id
$qty = '1'; // Replace qty with your qty
$_product = Mage::getModel('catalog/product')->load($id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($_product, array('qty' => $qty));
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
?>

The above code will programmatically add a product to cart. Ultimately, I'm going to test to see if the conditions of a shopping cart price rule are met and if so, run that could which adds a free "gift" or promotional product.

I've got my basic module configured. I'm just curious which event I should make use of that will allow me to add a product and update the cart? These appear to the applicable options:

  • checkout_cart_add_product_complete
  • checkout_cart_product_add_after
  • checkout_cart_update_items_before

So everytime a product from my catalog is added, an event is fired and my code is executed. Thanks in advance.

Best Answer

You should go for checkout_cart_add_product_complete (which is run in the addAction of the CartController). checkout_cart_update_items_before isn't appropriate for the action you're describing, and checkout_cart_product_add_after is triggered on addProduct, which will cause an issue because you are using this exact function in your observer.

Related Topic