Magento Themes and Magento Extensions

Create the checkout_cart_product_add_before observer in Magento

Share

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0"?>
<config>
...
<global>
...
<models>
<checkout>
<rewrite>
<cart>Foo_Bar_Model_Checkout_Cart</cart>
</rewrite>
</checkout>
</models>
...
</global>
...
</config>

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
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!

Comment: Milen Petrov

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.

Comments are closed.