Magento 2 Controller – Creating a Controller with Parameter

controllersmagento2magento2.2magento2.3parameter

I want to create the controller which get the parameter like

http://example.com/manufacturerpages/index/id/497

When I do this, It goes to 404 error plus I am also not able to get the id in controller by using this code

$mId = (int) $this->getRequest()->getParam('id', false);

I don't need the solution like

http://example.com/manufacturerpages/index?id/497

Because I have to use it in URL Rewrite so in that case, it is not working

Any help, experience and knowledge sharing would be appreciated.

Best Answer

As I worked on it, got the solution. First you need the create the di.xml to your module. As it is frontend custom router so you have to define it in etc\frontend. Type name for Router list addition is Magento\Framework\App\RouterList

Path should be like: app\code\Vendor\Module\etc\frontend\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">
    <type name="Magento\Framework\App\RouterList">
        <arguments>
            <argument name="routerList" xsi:type="array">
                <item name="customRouteForBlog" xsi:type="array">
                    <item name="class" xsi:type="string">Naheed\Manufacturerpages\Controller\Router</item>
                    <item name="disable" xsi:type="boolean">false</item>
                    <item name="sortOrder" xsi:type="string">20</item>
                </item>
            </argument>
        </arguments>
    </type>
</config>

Then you need to add the Router.php in your module file

Path should be like: app\code\Vendor\Module\Controller\Router.php. You need to define match function in your router file after than you can forward the request from wherever you want

class Router implements \Magento\Framework\App\RouterInterface
{
    public function  match(\Magento\Framework\App\RequestInterface $request) {
    }
}

As my work belongs to URL Rewrite. So I made a new URL Rewrite and define request path and target path for that. So when user hit the request it come on the match function then you will redirect it to request path

I hope this will help

Related Topic