2

I want to redirect to the home page (xyx.com) using the observer object & i am using the event controller_action_predispatch_cms_index_index.

below syntax is working fine when moving to the login page by the observer, Even I can move to any custom URL with the help of an observer object but unable to redirect to the home page.

below code is just for example. $observer->getControllerAction()->getResponse()->setRedirect('customer/account/login');

I have tried many solutions:

Try Solution 1 :

$observer->getControllerAction()->getResponse()->setRedirect('home');

but it will redirect to xyz.com/home

Try Solution 2: (a) $Url = $this->url->getUrl(''); OR (b) $Url = $this->url->getBaseUrl(); or (c) $Url = $this->url->getUrl('/');

& pass $Url to setRedirect but that is also not working.

 $observer->getControllerAction()->getResponse()->setRedirect($Url);

My Question is how to pass home page address to setRedirect.

Updated: Don't know the getUrl behaviour. Everthing thing is working & even custom url also working on getUrl on passing on observer & i am able to redirect anywhere accpording to my wish.

  $url =  getUrl('custom/url') or getUrl('home')
     or getUrl('customer/account/login')

all the above are working on setRedirect => $observer->getControllerAction()->getResponse()->setRedirect($url);

but $url = getUrl() is not working.

Does anyone face the same issue on redirection from observer. ?

  • Please check and update me. – Msquare Oct 15 at 11:52
  • Not working I want to redirect to home page (i.e xyz.com) but $myUrl = $this->url->getUrl('home'); echo $myUrl will give this path xyz.com/home – Pankaj Pant Oct 15 at 12:05
  • & $this->url->getUrl(); is the home page url & when i pass on setRedirect. It is not working – Pankaj Pant Oct 15 at 12:06
  • please check my answer magento.stackexchange.com/a/324428/82670 – Msquare Oct 15 at 12:45
1

Seems like you want to redirect Home page's cms page to Website index php

means redirect to xyz.com/home to xyz.com.

First, lets understand the router logic for these pages.

When You have hit xyz.com/home it called the Cms router Magento\Cms\Controller\Router and which hit the \Magento\Cms\Controller\Page\View action

Where, You have hit xyz.com/ its does not call the Cms router Magento\Cms\Controller\Router and it directly \Magento\Cms\Controller\Index\Index action

So, if you want to redirect /home to index page. then you have to work on on \Magento\Cms\Controller\Page\View::execute

Create an aroud plugin on it and redirect to home page.

<?php

declare(strict_types=1);

namespace StackExchanges\CmsRedirect\Plugin\Frontend\Magento\Cms\Controller\Page;

use Magento\Framework\UrlInterface;

class View
{
    /**
     * @var \Magento\Framework\Controller\Result\RedirectFactory
     */
    private $resultRedirectFactory;
    /**
     * @var UrlInterface
     */
    private $url;

    public function __construct(
        UrlInterface  $url,
        \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory
    ){

        $this->resultRedirectFactory = $resultRedirectFactory;
        $this->url = $url;
    }

    public function aroundExecute(
        \Magento\Cms\Controller\Page\View $subject,
        \Closure $proceed
    ) {
        $homePageCmsPageId = 1;
        $id = $subject->getRequest()->getParam('page_id') ?  $subject->getRequest()->getParam('id'):false;
        if($id!== 1){
            $result = $proceed();
        }
        $result = $this->resultRedirectFactory->create()->setUrl(
            $this->url->getBaseUrl()
        );
        return $result;
    }
}

Update

You need to add FLAG_NO_DISPATCH on this observer.

<?php


namespace StackExchanges\CmsRedirect;

use Magento\Framework\App\Action\Action;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\ActionFlag;
use Magento\Framework\App\Response\RedirectInterface;
use Magento\Store\Model\StoreManagerInterface;

class Redirect implements ObserverInterface
{

    /**
     * @var ActionFlag
     */
    private $actionFlag;
    /**
     * @var RedirectInterface
     */
    private $redirect;
    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    public function __construct(
        ActionFlag $actionFlag,
        RedirectInterface $redirect,
        StoreManagerInterface $storeManager
    )
    {
        $this->actionFlag = $actionFlag;
        $this->redirect = $redirect;
        $this->storeManager = $storeManager;
    }

    public function execute(Observer $observer)
    {
        /** @var Action $controller */
        $controller = $observer->getControllerAction();
        $this->actionFlag->set('', Action::FLAG_NO_DISPATCH, true);
        $controller->getResponse()->setRedirect($this->storeManager->getStore()->getBaseUrl());
    }
}
| improve this answer | |
  • Hi Amit, thanks for the valuable answer & understand the router logic. Actually I am using controller_action_predispatch_cms_index_index according to requirement. And I want to restrict the home page for some user or group id (Who is not the customer). They are merchants so that they can't access the home page after login. And I am able to do this & now the merchant can't access the home page. But the problem occurs when no one is login & simply I open the homepage & it redirects me to xyz.com/home & I have tried the different solutions but did not get success. – Pankaj Pant Oct 15 at 16:51
  • Pankaj, first, please your question properly. You question and comment are different . – Amit Bera Oct 15 at 17:09
  • yes but i want to know in my question why below code is not working $observer->getControllerAction()->getResponse()->setRedirect($this->url->getBaseUrl()); – Pankaj Pant Oct 15 at 17:16
  • After adding $this->actionFlag->set('', Action::FLAG_NO_DISPATCH, true); still recursion happen & Due to many redirect on homepage 500 internal error. – Pankaj Pant Oct 15 at 22:46
1

controller_action_predispatch_cms_index_index is the Home page predispatch & it is called always whenever the homepage hit by a User or it is called at the time of logout after a few seconds, when user come back to the homepage.

And this is not logical to redirect the same action But sometimes there is a requirement when we need to do this.

In Short words, In my question, I was asking why was $this->getUrl() is not working in $observer method.

i.e $observer->getControllerAction()->getResponse()->setRedirect($this->getUrl());

& I have done so many tried solution which are working inside setRedirect but expect homepage Url. Now I got to know why this is happening.

hahahaha... Reason: Due to recursion or you can say that

function abc() {
     abc();
}

abc();

I know, I did a very silly mistake & I am posting this as my answer so that no one can do this again.

| improve this answer | |
0
protected $responseFactory;
protected $url;

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

public function execute(\Magento\Framework\Event\Observer $observer)
{
    $myUrl = $this->url->getUrl('home'); //Get url of cms page
    $this->responseFactory->create()->setRedirect($myUrl)->sendResponse(); 
    die(); //This will stop execution and redirect to specific page
}
| improve this answer | |
0

Your solution 2 did not work ? what $Url returns ? Did you try to put '/' instead of 'home' ? if you put 'home' it calls the cms page called 'home'.

| improve this answer | |
  • try this one also, now updated. (c) $Url = $this->url->getUrl('/'); – Pankaj Pant Oct 15 at 10:49
0

Try This Code

<?php

namespace VendoreName\ModuleName\Observer;

use Magento\Framework\Event\ObserverInterface;

class YourObserverName implements ObserverInterface
{
    protected $_storeManager;

    public function __construct(
        ........................................................
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        ........................................................

    ) {
        ........................................................
        $this->_storeManager=$storeManager;
        ........................................................
    }
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $controller = $observer->getControllerAction();
        $url = $this->getHomeUrl();
        $controller->getResponse()->setRedirect($url);
        return $this;
    } 

    public function getHomeUrl()
    {
        $link = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK);
        $link .= "home";
        return $link;
    }

}
| improve this answer | |
  • Thanks for your answer but the code inside the getHomeUrl() function is equivalent to getUrl('Home') OR getBaseUrl('Home'). I have tried this also but it is redirecting xyz.com/home instead of xyz.com – Pankaj Pant Oct 15 at 15:49

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.