Jul 21, 2013
kalpesh

Magento redirect from observer

Redirection in observer doesn’t work normally as it do in Blocks, templates and controllers. Also there is no standard code to redirect from observer that works in every situation.

You will need an argument to achieve redirect when using below code:

1
2
3
4
public function observingMethod(Varien_Event_Observer $observer)
{
    $observer->getRequest()->setParam('return_url',$urlToRedirect);
}

Note that $observer object should have getRequest() method to make above code work. You may need to use $observer->getEvent()->getFront()->getRequest() otherwise, or simply var_dump/Mage::log $observer to get better idea what methods the object have.

Or you can use below code which is not recommended:

1
2
3
4
public function observingMethod() {
    header('Location: ' . $urlToRedirect);
    exit;
}

We don’t need any arguments using above method.

Another approach, again not recommended:

1
2
3
4
5
6
7
8
public function observingMethod(Varien_Event_Observer $observer)
{    
    $response = $observer->getResponse();
    //$response = Mage::app()->getFrontController()->getResponse();
    $response->setRedirect($urlToRedirect);

    Mage::app()->getFrontController()->sendResponse();
}

Leave a comment

 

Welcome to my Blog

Kalpesh MehtaHelping Magento developers in their day-to-day development problems since 2011. Most of the problems and solutions here are my own experiences while working on different projects. Enjoy the blog and don't forget to throw comments and likes/+1's/tweets on posts you like. Thanks for visiting!

Certifications