Magento Redirect from Observer

2019-07-29 04:43发布

问题:

I am having trouble to create a working redirect in Magento from an observer.Apart from that I need to understand why the exception just like we do in controller does not work in Observer.

The typical exception done in controller is like below (adminhtml controller)

$message = $this->__('Exception Message.');
Mage::getSingleton('adminhtml/session')->addError($message);
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;

Somewhere in the blog I read about the below method to redirect from observer.

Mage::getSingleton('core/session')->addError('Exception Message.');
Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl('checkout/cart'));
Mage::app()->getResponse()->sendResponse();
exit;

I don't understand the basic redirection difference when doing with an observer and controller.

Why controller redirection does not work when used in observer.

Please help me out and explain.

Thanks a lot in advance.

回答1:

See below link and i also have posted code it might help you.

Source : http://aaronbonner.io/post/418012530/redirects-in-magento-controllers

Redirects in Magento Controllers In Zend Framework controllers, to output something other than html you will want to disable ViewHelper defaults along with some of the other magic ZF typically weaves.

In Magento, the same thing applies when doing a controller redirect.

I noticed on PHP 5.2 a redirect seemed to be ignored whereas my Macports 5.3 setup it worked. Turns out I was missing a trick, and so a proper redirect in Magento is done as follows:

In MyPackage/MyModule/controllers/MyController.php :

$this->_redirectUrl($this->getUrl('http://www.someurl.com/someresource'));  
$this->setFlag('', self::FLAG_NO_DISPATCH, true);  
return $this;

Without the setFlag call, your redirect will be ignored. The return call stops any further code execution and sees your redirect get actioned.



标签: magento