Celldweller
Celldweller

Reputation: 309

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

Upvotes: 7

Views: 20535

Answers (4)

Lalit Kaushik
Lalit Kaushik

Reputation: 1062

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!

Upvotes: 9

Silas Palmer
Silas Palmer

Reputation: 201

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;

Upvotes: 20

HughieW
HughieW

Reputation: 149

That should work fine :s

Have you tried just exiting the script immediately after the setRedirect() call to see if it's definitely getting there?

Upvotes: 0

MagePal Extensions
MagePal Extensions

Reputation: 17656

Instead of creating a Observer, have you think about override the save news letter controller with your own custom module and do you spam logic there and then add the the news letter code below your logics.

You could also change the url for save news letter to a new custom module url then do your spam filter and if you think it is a valid email then you do a internal forward to the regular save news letter (see how to call one action from another in magento?)

Therefore you wouldn't have any issues redirecting from a controller

Upvotes: 0

Related Questions