0

I am trying to redirect a cms page to a custom controller. in router.php I can check the current URL, If the current URL is as an example if it matches /test-url i want to do a redirect to /test-url-router

    if ($identifier == 'test-url') {
       $this->_response->setRedirect('test-url-router');
       $request->setDispatched(true);
       return $this->actionFactory->create(\Magento\Framework\App\Action\Redirect::class);
    }

This works it does redirect me to test-url-router (the page will be 404) I want to show my custom controller which I am not sure of how to get this working.

$request->setModuleName('custom') //module name
        ->setControllerName('custom') //controller name
        ->setActionName('index'); //action name;

is it possible to get this both working?

1
  • Delete the cms page with test-url and create routes.xml and configure your own route. Commented Aug 20, 2021 at 15:44

1 Answer 1

0

Module name - Inchoo_CustomRouter

Registration.php :: app/code/Inchoo/CustomRouter/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Inchoo_CustomRouter', __DIR__
);

Module.xml :: app/code/Inchoo/CustomRouter/etc/module.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Inchoo d.o.o.
 * created by Zoran Salamun([email protected])
 * Module is created for Custom Router demonstration
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Inchoo_CustomRouter" setup_version="2.0.0"></module>
</config>

di.xml :: app/code/Inchoo/CustomRouter/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

</config>

routes.xml :: app/code/Inchoo/CustomRouter/etc/frontend/routes.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="inchootest" frontName="inchootest">
            <module name="Inchoo_CustomRouter" />
        </route>
    </router>
</config>

di.xml :: app/code/Inchoo/CustomRouter/etc/frontend/di.xml Here we are passing the router file path and the sort order for the router

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\App\RouterList">
        <arguments>
            <argument name="routerList" xsi:type="array">
                <item name="inchoocustomrouter" xsi:type="array">
                    <item name="class" xsi:type="string">Inchoo\CustomRouter\Controller\Router</item>
                    <item name="disable" xsi:type="boolean">false</item>
                    <item name="sortOrder" xsi:type="string">61</item>
                </item>
            </argument>
        </arguments>
    </type>
</config>

Routes.php :: app/code/Inchoo/CustomRouter/Controller/Router.php

<?php

namespace Inchoo\CustomRouter\Controller;

/**
 * Inchoo Custom router Controller Router
 *
 * @author      Zoran Salamun <[email protected]>
 */
class Router implements \Magento\Framework\App\RouterInterface {

    /**
     * @var \Magento\Framework\App\ActionFactory
     */
    protected $actionFactory;

    /**
     * Response
     *
     * @var \Magento\Framework\App\ResponseInterface
     */
    protected $_response;

    /**
     * @param \Magento\Framework\App\ActionFactory $actionFactory
     * @param \Magento\Framework\App\ResponseInterface $response
     */
    public function __construct(
    \Magento\Framework\App\ActionFactory $actionFactory, \Magento\Framework\App\ResponseInterface $response
    ) {
        $this->actionFactory = $actionFactory;
        $this->_response = $response;
    }

    /**
     * Validate and Match
     *
     * @param \Magento\Framework\App\RequestInterface $request
     * @return bool
     */
    public function match(\Magento\Framework\App\RequestInterface $request) {
        /*
         * You can use any name in URL and add condition for that name here to redirect it. Here we are accessing customrouting 
         * and if the we get the same, the we will redirect the request to controller action.
         * We will search “examplerouter” and “exampletocms” words and make forward depend on word
         * -examplerouter will forward to base router to match inchootest front name, test controller path and test controller class
         * -exampletocms will set front name to cms, controller path to page and action to view
         */
       // $a = explode('/', $_SERVER['REQUEST_URI']);
        // $postId = end($a);  [if you want to pass parameter also.]
        //exit;
        $identifier = trim($request->getPathInfo(), '/');
        if (strpos($identifier, 'exampletocms') !== false) {
            /*
             * We must set module, controller path and action name + we will set page id 5 witch is about us page on
             * default magento 2 installation with sample data.
             */
            $request->setModuleName('cms')->setControllerName('page')->setActionName('view')->setParam('page_id', 4); // specify the page id
        } else if (strpos($identifier, 'customrouting') !== false) {
            /*
             * We must set module, controller path and action name for our controller class(Controller/Test/Test.php)
             */
            $request->setModuleName('CustomRouter')->setControllerName('test')->setActionName('test');

            // $request->setParam('id', $postId); [if passing params]
        } else {
            //There is no match
            return;
        }

        /*
         * We have match and now we will forward action
         */
        return $this->actionFactory->create(
                        'Magento\Framework\App\Action\Forward', ['request' => $request]
        );
    }

}


/* you will face iteration error if the controller you are trying to access is not available*/

Test.php :: app/code/Inchoo/CustomRouter/Controller/Test/Test.php

<?php

/**
 * Copyright © 2015 Inchoo d.o.o.
 * created by Zoran Salamun([email protected])
 */

namespace Inchoo\CustomRouter\Controller\Test;

class Test extends \Magento\Framework\App\Action\Action {

    /**
     * Listing all images in gallery
     *  -@param gallery id
     */
    public function execute() {
        die("Inchoo\\CustomRouter\\Controller\\Test\\Test controller execute()");
    }

}
2
  • Hi Gohil, i am using this right now but i can't change the url, my default url is test-url and i need to redirect to test-url-routing with a custom controller. the /test-url is cms page
    – Tj1997
    Commented Aug 20, 2021 at 11:44
  • why u wanna redirect cms page url? I dont get your requirement. but you can also create redirect rule in htaccess Commented Aug 21, 2021 at 13:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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