Magento 2 : How to redirect from a observer without exit or die (as it's not allowed by magento standards)
-
07-10-2020 - |
Question
I know of a couple of ways of redirecting to a given URL in observer but all of them uses exit or die and they would not work without it. So, if someone knows of a way of doing it without using exit or die then please let me know.
Solution
use setRedirect
<?php
namespace [Vendor]\[modulename]\Observer;
use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;
class [YourClass] implements ObserverInterface {
protected $_responseFactory;
protected $_redirect;
protected $_url;
public function __construct(
......
\Magento\Framework\App\ResponseFactory $responseFactory,
\Magento\Framework\UrlInterface $url,
\Magento\Framework\App\Response\Http $redirect,
......
) {
$this->_responseFactory = $responseFactory;
$this->_url = $url;
$this->_redirect = $redirect;
}
public function execute(Observer $observer) {
$event = $observer->getEvent();
$CustomRedirectionUrl = $this->_url->getUrl('[ModuleName]/[ModuleName]/[[Action]');
$this->_redirect->setRedirect($CustomRedirectionUrl);
}
}
OTHER TIPS
Without exit or die redirecting to a given URL in observer you need to stop the dispatch event using Action::FLAG_NO_DISPATCH
namespace [Vendor]\[modulename]\Observer;
use Magento\Framework\Event\ObserverInterface;
class [YourClass] implements ObserverInterface {
protected $urlManager;
protected $actionFlag;
protected $redirect;
public function __construct(
......
\Magento\Framework\UrlInterface $url,
\Magento\Framework\App\ActionFlag $actionFlag,
\Magento\Framework\App\Response\RedirectInterface $redirect,
......
) {
$this->urlManager = $url;
$this->actionFlag = $actionFlag;
$this->redirect = $redirect;
}
public function execute(\Magento\Framework\Event\Observer $observer) {
$controller = $observer->getControllerAction();
// stop the dispatch event.
$this->actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);
//YOUR-ACTION eq to ex. for create acount '*/*/create'
$defaultUrl = $this->urlManager->getUrl('YOUR-ACTION', ['_secure' => true]);
$controller->getResponse()->setRedirect($this->redirect->error($defaultUrl));
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange