Magento2 redirection from Observer
Magento2 redirection from Observer needs serval times.In Some events, you need to forcefully redirect to some pages basic your business logic.
At magento 1.x,we can do using Mage::app()->getResponse()->setRedirect(‘YourRedirectUrl’)->sendResponse();
Something is required forMagent0 2.X version.This version uses modern technologies Namespace, interface, Factory class etc.So there not easy to do a redirection from an Observer.
Most case, developer need to implement forceful redirection to Observer as per their client requirement
I have found a solution by myself by doing a research
If you want to do that then you should below inject two classes.
\Magento\Framework\App\ResponseFactorywhich responsible for redirection,
- Another class which
\Magento\Framework\UrlInterfacewill make an url for that redirection.(This can optional).
- Then You should create a response Object $this->_response->create() from
- Then using method setRedirect() and sendResponse(),you can redirect url.Where setRedirect() set url for redirection and sendReponse() send response this url.
Case1: For Controllers events
If want redirection from Observer for an event which has controller_action object as it events parameters
Then time, my suggestion avoid using
If you have controller_action object and by injecting \Magento\Framework\App\ActionFlag then using below code you redirect to your desired URL
Here i am written an example of that redirection.
I have used event,
Here the observer code:
Controller event example:
For this case ,I have used event controller_action_postdispatch_newsletter_subscriber_newI was trying to forcefully redirect to Customer login page