Magento 2 Category URL Redirect to Custom Controller

categorycontrollersmagento2redirect

I have add one category from backend, I need to redirect that category url to custom module controller(chennaievent\index\index).

<?php
namespace Gworks\Chennaievent\Observer;
use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;

class Redirect implements ObserverInterface {
    protected $_responseFactory;
    protected $_url;

    public function __construct(

    \Magento\Framework\App\ResponseFactory $responseFactory,
    \Magento\Framework\UrlInterface $url
    ) {
    $this->_responseFactory = $responseFactory;
    $this->_url = $url;
    }

    public function execute(Observer $observer) {
         $category = $observer->getEvent()->getCategory();
       if($category->getId()=='115'){   
     $controllerAction=$observer->getEvent()->controllerAction();    
     $RedirectUrl= $this->_url->getUrl('chennaievent/index/index');
     $this->_responseFactory->create()->setRedirect($RedirectUrl)->sendResponse();
       exit();
    }
    }
}

when I click newly added category its redirect to page not found(404) without URL change,I have tried without single quotes also getId()==115

How could I achieve category url redirect to custom controller?

Thanks.

Best Answer

In order to full fill your requirement, can to use Event/Observer

Create a custom module and using catalog_controller_category_init_after event for redirect to your custom url

see Magento2: redirection from Observer

<?php
namespace [Vendor]\[modulename]\Observer;
use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;

class [YourClass] implements ObserverInterface {
    protected $_responseFactory;
    protected $_url;

    public function __construct(

        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url
    ) {
        $this->_responseFactory = $responseFactory;
        $this->_url = $url;
    }

    public function execute(Observer $observer) {
             $category = $observer->getEvent()->getCategory();
       if($category->getId()=='Match_CatID'){   
         $controllerAction=$observer->getEvent()->getControllerAction() 
             $RedirectUrl= $this->_url->getUrl('chennaievent\index\index');
            $this->_responseFactory->create()->setRedirect($RedirectUrl)->sendResponse();
           exit();
        }
    }
}