Skip to main content

Magento 2: How to use redirect URl in Router.php

Module name - **Aks_CustomUrlRouter**

You have to create below listed files

1. Registration.php :: app/code/Aks/CustomUrlRouter/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(

    \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Aks_CustomUrlRouter', __DIR__

);

?>

2. Module.xml :: app/code/Aks/CustomUrlRouter/etc/module.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">

    <module name="Aks_CustomUrlRouter" setup_version="2.0.0"></module>

</config>

3. di.xml :: app/code/Aks/CustomUrlRouter/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>

4. routes.xml :: app/code/Aks/CustomUrlRouter/etc/frontend/routes.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">

    <router id="standard">

        <route id="aksurlrouter" frontName="aksurlrouter">

            <module name="Aks_CustomUrlRouter" />

        </route>

    </router>

</config>

5. di.xml :: app/code/Aks/CustomUrlRouter/etc/frontend/di.xml

Here we need to passing the router file path and the sort order for the router

<?xml version="1.0" encoding="UTF-8"?>

<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="akscustomurlrouter" xsi:type="array">

                    <item name="class" xsi:type="string">Aks\CustomUrlRouter\Controller\Router</item>

                    <item name="disable" xsi:type="boolean">false</item>

                    <item name="sortOrder" xsi:type="string">61</item>

                </item>

            </argument>

        </arguments>

    </type>

</config>

6.Routes.php :: app/code/Aks/CustomUrlRouter/Controller/Router.php

<?php

namespace Aks\CustomUrlRouter\Controller;

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) {

        /*

         * We can use any name of the URL to add and make condition for that name for redirect it. Here we can get customrouting 

         * If we got the same url it will redirect the request to controller action.

         * If we want to search “examplerouter” and “exampletocms” words to redirect the cutom router

         * using this example -examplerouter will forward to base router to match aksurlrouter front name, test the controller path and test controller class

         * -exampletocms will set for front name to cms, and controller path to page and action to view

         */

        //$a = explode('/', $_SERVER['REQUEST_URI']);

        //$postId = end($a);  [if you want to pass parameter also.]

        $identifier = trim($request->getPathInfo(), '/');

        if (strpos($identifier, 'exampletocms') !== false) {

            /* We must set module name, controller path and action name within need to 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 name, controller path and action name for our controller is class(Controller/Test/Test.php)

            */

            $request->setModuleName('CustomRouter')->setControllerName('test')->setActionName('test');

            // $request->setParam('id', $postId); [if passing params]

        } else {

            //If it 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 is not available you have to trying to access*/

?>

7. Test.php :: app/code/Aks/CustomUrlRouter/Controller/Test/Test.php

<?php

namespace Aks\CustomUrlRouter\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()");

    }

}

Comments

Popular posts from this blog

Magento 2 How to get product collection using controller

Getting product collection in Magento 2 Step 1: Declare in Vendor_ModuleName Block Step 2: Display product collection in phtml file .. Step 1: Declare in Vendor_ModuleName Block You will use a block class of the module Vendor_ModuleName, then possibly inject the object of `\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory` in the constructor of the module’s block class.     app/code/Vendor/ModuleName/Block/ProductCollection.php add code this code  <?php namespace Vendor\ModuleName\Block; class ProductCollection extends \Magento\Framework\View\Element\Template { protected $_productCollectionFactory; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory, array $data = [] ) { $this->_productCollectionFact...

Magento 2 get category collection using specific controllers and category level using object manager

Magento 2 get category collection using object manager <?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $category = $objectManager->get('Magento\Framework\Registry') ->registry('current_category'); //get current category $requestInterface = $objectManager->get('Magento\Framework\App\RequestInterface'); //echo $routeName = $requestInterface->getRouteName(); //echo $moduleName = $requestInterface->getModuleName(); $controllerName = $requestInterface->getControllerName(); //echo $actionName = $requestInterface->getActionName(); $parcatId = $category->getId(); // current Category ID $parcategory = $objectManager->create('Magento\Catalog\Model\Category') ->load($parcatId); $parent_category = $parcategory->getParentCategory(); $subcatId = $parent_category->getId(); $subcategory = $objectManager->create('Magento\Catalog\Model\Category...

Magento 2 add single product using custom script or programmatically

Magento 2 add single product programmatically <?php //increase the max execution time @ini_set('max_execution_time', -1); //memory_limit @ini_set('memory_limit', -1); error_reporting(E_ALL); ini_set('display_errors', '1'); use \Magento\Framework\App\Bootstrap; require __DIR__ . '/app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER); $bootstrapManager = $bootstrap->getObjectManager(); $state = $bootstrapManager->get('\Magento\Framework\App\State'); $state->setAreaCode('frontend'); $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager $product = $objectManager->create('\Magento\Catalog\Model\Product'); $sku = 'sku'; $name = 'Sample Product'; $product->setSku($sku); // Set your sku here $product->setName($name); // Name of Product $product->setAttributeSetId(4); // Attribu...