Wednesday, September 11, 2013

Simple method to trigger a custom event in magento

Here is a simple method to trigger a custom event using an action (e.g after upload ) in a custom module

for this you need to edit in three files
one in controller,then in a model observer and last in config.xml


Open custom modules controller file and add the following code in the controller function

e.g
<?php
.
.
.
.
function upload{

$uploader->save($path, $_FILES['name']['name']);

    //Custom event to load function in oberser.php
  Mage::dispatchEvent('file_upload_save_after', array('path' => array($path)));
}
.
.
.
.
?>

This triggers an observer event and the default observer catches the event.In
model create a file named observer.php and add the following code

<?php
class Mage_File_Model_Observer
{
 public function convertFile($observer)
    {  
 
 
     $order_ids = $observer->getEvent()->getOrderIds(); //$order_ids is the array containg the od of the order placed
   
            //Hooking to our own event
      $path = $observer->getEvent()->getpath();
       echo '<pre>';
       print_r($path);
           // do something with product
       //Mage::log("Product ".$request['product']." is added to cart.");
     
     /*    //your code goes here    
       return $this;*/
       exit(__METHOD__);
    }
}



finally declare the event name and parameters in modules config.xml file as follows
.
.
.
.

    <events>
     
            <file_upload_save_after>
               <observers>
                   <file>
                       <class>file/Observer</class>
                       <method>convertFile</method>
                   </file>
               </observers>
           </file_upload_save_after>
         
 </events>

.
.
.
.

No comments:

Post a Comment