Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento Redirect from Observer that always works

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 :)

like image 604
Celldweller Avatar asked Nov 05 '12 17:11

Celldweller


2 Answers

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;
like image 80
Silas Palmer Avatar answered Oct 09 '22 03:10

Silas Palmer


I am going to short and correct Silas Palmer's code.

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

hope this helps someone!

like image 31
Lalit Kaushik Avatar answered Oct 09 '22 01:10

Lalit Kaushik