Magento 2.x – how to force redirect to controller on observer
In this tutorial i am going to show you how to redirect a user to any particular controller. This was made on an observer, but could be potentially used in any scenario.
This was developed taking as reference how the \Magento\Customer\Model\Session::authenticate() method works.
Observer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php namespace [Vendor]\[modulename]\Observer; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; class [YourClass] implements ObserverInterface { /** * @var \Magento\Framework\App\ResponseFactory */ private $_response; /** * @var \Magento\Framework\UrlInterface */ private $_url; public function __construct( ...... \Magento\Framework\UrlInterface $url, \Magento\Framework\App\Response\Http $response ...... ) { $this->_url = $url; $this->_response = $response; } public function execute(Observer $observer) { // as example, we will redirect to customer dashboard, but should be like this: '[ModuleName]/[ModuleName]/[[Action]' $redirectionUrl = $this->_url->getUrl('customer/account'); $this->_response->setRedirect($redirectionUrl); } } |
After that, remember to proceed with recompiling, as follows:
1 2 |
rm -rf generated/* php bin/magento setup:di:compile |
And that’s it. Happy coding!
Be safe. #StayAtHome #QuedateEnCasa.