Magento Redirect from Observer that always works

Celldweller picture Celldweller · Nov 5, 2012 · Viewed 19.8k times · Source

I am having trouble to create a working redirect in Magento from an observer.

As far as I know there are many events that got the response object with them (in the $observer object). Another way would be to use something like

Mage::app()->getResponse()->setRedirect(Mage::getUrl('checkout/cart'));

as mentioned here https://stackoverflow.com/a/4730200/1700048 by the great Alan Storm.

Unfortunately this does not work for me, even when I add sendResponse() like this:

Mage::app()->getResponse()->setRedirect(Mage::getUrl('checkout/cart'))->sendResponse();

For example:

I want to prevent some email addresses to newsletter subscription. Therefore I created an observer for the newsletter_subscriber_save_before Event.

In my observer method I check some cases and if they trigger I want to prevent the saving of the newsletter subscribtion. My plan was to add an error like this:

Mage::getSingleton('checkout/session')->addError('Email is spam!');

and just let the current page reload (showing the error message) with a redirect as seen above (checkout/cart in the example is just to see it really works).

Unfortunately the redirect does not work. Why does sendResponse not send the response in this case?

Thanks for help :)

Answer

Silas Palmer picture Silas Palmer · Feb 13, 2013

This works but it is not super elegant:

Mage::getSingleton('core/session')->addError('Email is spam!');
Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl('checkout/cart'));
Mage::app()->getResponse()->sendResponse();
exit;