1

How to create a custom route in Magento 2

http://127.0.0.1/magento8/trails/post/view/id/13

module:- trails

folder :-post

controller :- view

argument :-id/13

I want to http://127.0.0.1/magento8/slug/

enter image description here

anyone help me

2

Just create an entry in Admin Panel > Marketing > SEO & Search > URL Rewrites

with request path as slug and target path as trails/post/view/id/13

This should help.

2

You have to create a custom router.

First define custom router

Create di.xml at app/code/Vendor/Module/etc/ and define the custom router

<?xml version="1.0"?>
<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="customrouter" xsi:type="array">
                  <item name="class" xsi:type="string">{Vendor}\{Module}\Controller\CustomRouter</item>
                  <item name="disable" xsi:type="boolean">false</item>
                  <item name="sortOrder" xsi:type="string">22</item>
              </item>
          </argument>
      </arguments>
  </type>
</config>

2. custom router point your slug to trails/post/view/id/13

Use of custom router means to point a custom URL http://example.com/index.php/mytesturl/ to Magento own routing http://example.com/index.php/front_name/controller/action/ . On custom router match request path slug with

<?php

namespace {Vendor}\{Module}\Controller;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class CustomRouter implements \Magento\Framework\App\RouterInterface
{
    /**
     * @var \Magento\Framework\App\ActionFactory
     */
    protected $actionFactory;

    /**
     * Event manager
     *
     * @var \Magento\Framework\Event\ManagerInterface
     */
    protected $_eventManager;

    /**
     * Store manager
     *
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;

    /**
     * Config primary
     *
     * @var \Magento\Framework\App\State
     */
    protected $_appState;

    /**
     * Url
     *
     * @var \Magento\Framework\UrlInterface
     */
    protected $_url;

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

    /**
     * @param \Magento\Framework\App\ActionFactory $actionFactory
     * @param \Magento\Framework\Event\ManagerInterface $eventManager
     * @param \Magento\Framework\UrlInterface $url

     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Framework\App\ResponseInterface $response
     */
    public function __construct(
        \Magento\Framework\App\ActionFactory $actionFactory,
        \Magento\Framework\Event\ManagerInterface $eventManager,
        \Magento\Framework\UrlInterface $url,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\App\ResponseInterface $response
    ) {
        $this->actionFactory = $actionFactory;
        $this->_eventManager = $eventManager;
        $this->_url = $url;
        $this->_storeManager = $storeManager;
        $this->_response = $response;
    }

    /**
     * Validate and  modify request
     *
     * @param \Magento\Framework\App\RequestInterface $request
     * @return \Magento\Framework\App\ActionInterface|null
     */
    public function match(\Magento\Framework\App\RequestInterface $request)
    {
        $identifier = trim($request->getPathInfo(), '/');

        $condition = new \Magento\Framework\DataObject(['identifier' => $identifier, 'continue' => true]);

        $identifier = $condition->getIdentifier();

        if ($condition->getRedirectUrl()) {
            $this->_response->setRedirect($condition->getRedirectUrl());
            $request->setDispatched(true);
            return $this->actionFactory->create(\Magento\Framework\App\Action\Redirect::class);
        }

        if (!$condition->getContinue()) {
            return null;
        }


    if (($condition->getContinue() == {slug}) {
         $request->setModuleName('trails')->setControllerName('post')->setActionName('view')->setParam('id', 13);
        $request->setAlias(\Magento\Framework\Url::REWRITE_REQUEST_PATH_ALIAS, $identifier);

        return $this->actionFactory->create(\Magento\Framework\App\Action\Forward::class);
        }
    return null
    }
}
  • if (($condition->getContinue() == {slug}) { undefine error {slug} – Nitesh Kumar Singh May 18 '18 at 13:00
  • You that {slug} with your slug – Amit Bera May 18 '18 at 13:17
  • 127.0.0.1/magento8/test1 if (($condition->getContinue() == 'test1')) { getting error 404 Whoops, our bad... – Nitesh Kumar Singh May 18 '18 at 13:36
  • @AmitBera How magento will know that for this particular route it needs to use this router? – Sarvagya Feb 25 at 9:06
  • The code if (($condition->getContinue() == {slug}) { $request->setModuleName('trails')->setControllerName('post')->setActionName('view')->setParam('id', 13); $request->setAlias(\Magento\Framework\Url::REWRITE_REQUEST_PATH_ALIAS, $identifier); return $this->actionFactory->create(\Magento\Framework\App\Action\Forward::class); } As per as your business logic ,you have to map your router – Amit Bera Feb 25 at 9:08
0

Steps :

  1. Create a new file in trails/post/etc/config.xml and copy following content :
<?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="slug" frontName="slug">
            <module name="trails_post" />
        </route>
    </router>
</config>
  1. Rename controller to Index
  • Please accept the answer also. If it works. – mighty_hk May 18 '18 at 12:48
  • folder structure my module – Nitesh Kumar Singh May 18 '18 at 12:51

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.