Adding an Event Observer

An event listener (observer) is used when you want to hook in to an event.

Posted on March 25, 2016 in Magento

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 <global> tag
    <events>
        <helloworld_register_visit>
            <observers>
                <register_visit>
                     <type>singleton</type>
                     <class>helloworld/observer</class>
                     <method>registerVisit</method>
                </register_visit>
            </observers>
        </helloworld_register_visit>
    </events>
    
    

  • 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 <events> tag
    <checkout_cart_product_add_after>
        <observers>
            <check_cart_qty>
                <type>singleton</type>
                <class>helloworld/observer</class>
                <method>checkCartQty</method>
            </check_cart_qty>
        </observers>
    </checkout_cart_product_add_after>
    
    

  • 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. ");
       }
    }
    
    


comments powered by Disqus