I need to redirect the customer to a certain URL from a observer after I log him in with loginById
.
How can I redirect?
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityYou can get your current url in the observer using
use Magento\Framework\App\ResponseFactory;
use Magento\Framework\UrlInterface;
use Magento\Framework\App\Response\Http
/**
* @var UrlInterface
*/
protected $_urlInterface;
/**
* @var ResponseFactory
*/
protected $responseFactory;
public function __construct(
ResponseFactory $responseFactory,
UrlInterface $urlInterface,
Http $request,
) {
$this->responseFactory = $responseFactory;
$this->_urlInterface = $urlInterface;
$this->request = $request;
}
Get the current url
$currentUrl = $this->_urlInterface->getCurrentUrl();
Then just filter to get the condition of the current url you want
Then redirect anywhere you want
$redirectUrl = "any url you want";
$resultRedirect = $this->responseFactory->create();
$resultRedirect->setRedirect($redirectUrl)->sendResponse('302');
NB: You can also retrieve the current action name it can be usefull
$fullActionName = $this->request->getFullActionName();
I solved it with:
header("Location: $url");
exit;
loginById
function? Controller or model?
If you using Magento\Framework\App\ActionFlag
then you redirect from controller_action_predispatch
<?php
namespace VendorName\ModuleName\Observer;
use Magento\Framework\Event\ObserverInterface;
class MyObserver implements ObserverInterface
{
/**
* @var \Magento\Framework\App\ActionFlag
*/
protected $_actionFlag;
/**
* @var \Magento\Framework\Message\ManagerInterface
*/
protected $messageManager;
/**
* @var \Magento\Framework\App\Response\RedirectInterface
*/
protected $redirect;
/**
* @param \Magento\Framework\App\ActionFlag $actionFlag
* @param \Magento\Framework\Message\ManagerInterface $messageManager
* @param \Magento\Framework\App\Response\RedirectInterface $redirect
*/
public function __construct(
\Magento\Framework\App\ActionFlag $actionFlag,
\Magento\Framework\Message\ManagerInterface $messageManager,
\Magento\Framework\App\Response\RedirectInterface $redirect
) {
$this->_actionFlag = $actionFlag;
$this->messageManager = $messageManager;
$this->redirect = $redirect;
}
/**
* execute function
*
* @param \Magento\Framework\Event\Observer $observer
* @return $this
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
/** @var \Magento\Framework\App\Action\Action $controller */
$controller = $observer->getControllerAction();
if (MYCondition) {
$this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);
$this->redirect->redirect($controller->getResponse(), 'YourUrlToRedirect');
}
return $this;
}
}