0

I facing issue while redirect from observer file. Actually code worked on localhost but on the server it's not working. Here is the code

public function execute(\Magento\Framework\Event\Observer $observer)
{
    $route = $this->request->getControllerName();
    $url = $this->url->getUrl('customer/account/login');
    if($this->getStoreCode() == 'default'){
        if (!$this->customerSession->isLoggedIn()) {
            if($this->_state->getAreaCode() != 'adminhtml') {
                if(strpos($this->request->getPathInfo(), '/customer/account/') !== 0 || $route == 'noroute') {
                    $observer->getControllerAction()->getResponse()->setRedirect($url);
                }
            }
        }
    }
}

It is not working while controller is noroute. Can anyone please suggest if faced same issue.

1
  • On which event you have fire this observer?
    – Amit Bera
    Jun 23, 2019 at 4:30

1 Answer 1

0

Use this code for redirect

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class [YourClass] implements ObserverInterface
{
    /**
     * @var \Magento\Framework\App\ResponseFactory
     */
    private $responseFactory;

    /**
     * @var \Magento\Framework\UrlInterface
     */
    private $url;

    public function __construct(
        ......
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url,
        ......
    ) {
        $this->responseFactory = $responseFactory;
        $this->url = $url;
    }

    public function execute(Observer $observer)
    {
        $redirectionUrl = $this->url->getUrl('[ModuleName]/[ModuleName]/[[Action]');
        $this->responseFactory->create()->setRedirect($redirectionUrl)->sendResponse();

        return $this;
    }
}
4
  • I use that one also but there we need to place exit(); And it is not good practice as magento says.
    – Ravi Soni
    Jun 22, 2019 at 12:19
  • dont need to add exit it will work without it
    – MageCoder
    Jun 22, 2019 at 13:24
  • Is it working for You? I checked and there is no error and no redirect.
    – BartZalas
    Jun 24, 2019 at 23:28
  • yes it is working code
    – MageCoder
    Jun 25, 2019 at 5:23

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.