In this tutorial, will add two event observer. The first one will catch the event that we created in the Creating Your Own Event In Magento. The second event listener will observe the “add to cart” action of a product.
The following steps describe what we can do with event observers:
- To listen to the helloworld_register_visit event, we have to add configuration to the config.xml file of the Jeff_Helloworld module. Add the following code under the <global> tag:
#under tag singleton helloworld/observer registerVisit -
We just configured an observer that handles the registerVisit() function of the helloworld/observer class. We have to create the Jeff_Helloworld_Model_Observer class and add registerVisit() method in it:
#app/code/local/Jeff/Helloworld/Model/Observer.php class Jeff_Helloworld_Model_Observer { public function registerVisit( Varien_Event_Observer $observer) { $product = $observer->getProduct(); $category = $observer->getCategory(); Mage::log($product->debug()); Mage::log($category->debug()); } } -
Next, we will create an event listener for the event checkout_cart_product_add_after. We do this by adding the following code in the config.xml file of the Jeff_Helloworld module.
#under tag singleton helloworld/observer checkCartQty -
This will call the checkCartQty() function in the observer class. The following code will display a notice message when the event is fired and check if the quantity is odd or even.
public function checkCartQty($observer) { if ($observer->getProduct()->getQty() %2 == 0) { Mage::getSingleton('checkout/session')->addNotice('Product add event fired.'); } else { Mage::getSingleton('checkout/session')->addNotice("Quantity is odd. "); } }