Create the checkout_cart_product_add_before observer in Magento

Want to learn something new? Check out my most recent Egghead course:

Build a Twelve-Factor Node.js App with Docker - WATCH NOW on!

Cheers -Mark

Mon, 08/27/2012 - 11:12

Submitted by markoshust Mon, 08/27/2012 - 11:12

For some reason no one can explain, it appears that the event observer checkout_cart_product_add_before never existed in Magento (even though checkout_cart_product_add_after does). Say what?!??

Anyways, it's fairly easy to go ahead and dispatch this event. Just add this to your module's config.xml to rewrite the checkout/cart model:

<?xml version="1.0">

Then create your model that adds in the dispatch event to trigger the observers:

class Foo_Bar_Model_Checkout_Cart extends Mage_Checkout_Model_Cart
     * Create checkout_cart_product_add_before event observer
     * @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);
        Mage::dispatchEvent('checkout_cart_product_add_before', array('product' => $product));
        return parent::addProduct($productInfo, $requestInfo=null);

Now you can have fun triggering checkout_cart_product_add_before event observers! Enjoy!


Hi Mark, thanks a lot for this article. I want to propose another way of doing it, which i think is more proper and does not conflict with other extensions which may override the AddProduct controller. My idea is very simple: Simply create a new module and create an observer for controller_action_predispatch event. Then inside the observer simply check if($observer->getEvent()->getControllerAction()->getFullActionName() == 'checkout_cart_add') { Mage::dispatchEvent('checkout_cart_product_add_before', $any_params_you_want_to_pass); } return $this; I think thus way we can even more extend cart actions and add events for checkout_cart_update_before/after and checkout_cart_delete_before/after. Thus way our extension will be not conflicting with any third party one which overrides the cart controller. Any thoughts are welcome

Milen, Great suggestion, that is also another way to do it (and is in fact probably a 'better' way). Thanks for the idea!