I’m trying redirect to the login when some guess user press the add cart button and he is not registered. But i can’t do it. I am usin a Observer, with the following event
this is my /app/code/vendor/module/etc/frontend/event.xml
event.xml
< ?xml version="1.0"?>
and my Observer/app/code/vendor/module/Observer/ForceLogin.php
ForceLogin.php
< ?php
namespace vendormoduleObserver;
use MagentoFrameworkEventObserverInterface;
class ForceLogin implements ObserverInterface
{
protected $_responseFactory;
protected $_url;
private $scopeConfig;
private $customerSession;
private $customerUrl;
private $context;
private $contextHttp;
protected $redirect;
public function __construct(
MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
MagentoFrameworkAppActionContext $context,
MagentoCustomerModelSession $customerSession,
MagentoFrameworkAppHttpContext $contextHttp,
MagentoCustomerModelUrl $customerUrl,
MagentoFrameworkAppResponseFactory $responseFactory,
MagentoFrameworkAppResponseRedirectInterface $redirect,
MagentoFrameworkUrlInterface $url
) {
$this->scopeConfig = $scopeConfig;
$this->context = $context;
$this->customerSession = $customerSession;
$this->customerUrl = $customerUrl;
$this->contextHttp = $contextHttp;
$this->messageManager = $context->getMessageManager();
$this->_responseFactory = $responseFactory;
$this->_url = $url;
$this->redirect = $redirect;
}
public function execute(MagentoFrameworkEventObserver $observer)
{
$isLoggedIn = $this->contextHttp->getValue(MagentoCustomerModelContext::CONTEXT_AUTH);
if (!$isLoggedIn ) {
$this->messageManager->addError(__('Loggin First.'));
$customRedirectionUrl = $this->_url->getUrl('customer/account/login');
$this->_responseFactory->create()->setRedirect($customRedirectionUrl)->sendResponse('200');
exit();
}
return $this;
}
}
Any idea why he is not doing the redirect?