1

I'm trying to redirect guest users to the login page when they click on the Add to Cart button and they are not registered. But I can't do it. I am using an Observer with the following event

<event name="controller_action_predispatch_checkout_cart_add">

Below code is for /app/code/vendor/module/etc/frontend/event.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch_checkout_cart_add">
        <observer name="restrict_sales_model_cart_add_before" instance="vendor\module\Observer\ForceLogin" />
    </event>
</config>

And below code is for Observer /app/code/vendor/module/Observer/ForceLogin.php

<?php

namespace vendor\module\Observer;

use Magento\Framework\Event\ObserverInterface;

class ForceLogin implements ObserverInterface
{
    protected $_responseFactory;
    protected $_url;
    private $scopeConfig;
    private $customerSession;
    private $customerUrl;
    private $context;
    private $contextHttp;
    protected $redirect;

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Framework\App\Action\Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\App\Http\Context $contextHttp,
        \Magento\Customer\Model\Url $customerUrl,
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\App\Response\RedirectInterface $redirect,
        \Magento\Framework\UrlInterface $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(\Magento\Framework\Event\Observer $observer)
    {
        $isLoggedIn = $this->contextHttp->getValue(\Magento\Customer\Model\Context::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 guest users are not redirecting to the login page?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.