Magento observer


When it comes to customize the magento code, there are following 4 options:


1. Creating a observer should be the first to consider.


2. Extending and overriding the core modules should be the second to consider when option 1 cannot fails to accomplish the objectives.


3. Copy the core class to the local directory and put it in the same directory path it was in core directory, this is should be avoided.


4. Modify the core class directly, this should definitely be avoided unless you are just trying to test a code snippet.
So, there are really only two recommended options which is to try to create an observer first, if it doesn’t work out then write a module to extend and override the core module.

Here is an example of how to create an observer in Magento. This module has two observer:


First one: When observed a product is added to the cart, print some messages.


Second one: To observe when a product review is submitted. The default Magento behavior is to save the product review with PENDING status, this observer will auto approve the submitted product review instead.

1. Create a xml file app/etc/modules/MyExtensions_Observerdemo.xml
<global> applys to both frontend and backend
<fronend> applys only applys to frontend
<adminhtml> applys only applys to backend

3. Create a php file app/code/local/MyExtensions/Observerdemo/Model/Observer.php


<?php
class MyExtensions_Observerdemo_Model_Observer {
    public function addtocartEvent(Varien_Event_Observer $observer) {
        $event = $observer->getEvent();  //Gets the event      
$product = $event->getProduct();      
$observermsg = "The event triggered>>> <B>" . $event->getName() . "</B><br/> The added product>>> <B> " . $product->getName()."</B>";        //Adds the message to the shopping cart      
echo Mage::getSingleton('checkout/session')->addSuccess($observermsg);  
}  
    public function autoApproveReview(Varien_Event_Observer $observer){      
$event = $observer->getEvent();      
$reviewObjData = $event->getData();      
//print_r($reviewObjData);exit;
        $reviewData=$reviewObjData["data_object"];      
$reviewData->setStatusId(Mage_Review_Model_Review::STATUS_APPROVED);      
        echo Mage::getSingleton('core/session')->addSuccess("Thank you for your input!!");    }}


4. Clear cache, go to the frontend, add a product and submit a review to see what happens.



Rakesh Singh Uniyal

I’m Rakesh Singh Uniyal (MCA) and I write to help people work on programming and technology. The tips, tutorials and information provided in this blog has helped many people to solve their programming and web development related issues.
I work as a Freelance PHP/Magento/Wordpress Developer.

No comments:

Post a Comment