Magento Redirect from Observer that always works

血红的双手。 提交于 2019-12-09 17:05:01

问题


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


回答1:


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;



回答2:


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!




回答3:


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




回答4:


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?



来源:https://stackoverflow.com/questions/13236912/magento-redirect-from-observer-that-always-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!