1

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.

  • its working after comment this line " $controllerAction=$observer->getEvent()->controllerAction();" – Bilal Usean May 3 '16 at 13:45
4

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();
        }
    }
}
  • thanks, but its redirect to page not found without url change, old url only present.I have updated my question – Bilal Usean May 3 '16 at 13:34
  • its working after comment this line " $controllerAction=$observer->getEvent()->controllerAction();" – Bilal Usean May 3 '16 at 13:42

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.