0

I am on Magento 2.1 and I have looked all over and cannot find how to accomplish what I'm looking for. I've followed a few guides (http://inchoo.net/magento-2/how-to-create-a-basic-module-in-magento-2/ etc) on how to create basic controllers and I have accomplished that. But I am trying to make a controller which brings me to a list of all my brands in my store, and then when clicking one of the brands it brings me to a page with all of the materials for that brand.

Currently I have a module with the following structure:

Brands
  Block
     Brand.php
     Brands.php
  Controller
     Brand
        Index.php
     Index
        Index.php
  etc
     frontend
        routes.xml
     module.xml
  view
     frontend
        layout
           brands_brand_index.xml
           brands_index_index.xml
        templates
           brand.phtml
           brands.phtml
  registration.php

Currently when I go to mydomain/brands or mydomain/brands/index/index, it works as expected (bringing up a list of all brands). The same is true for mydomain/brands/brand or mydomain/brands/brand/index.

My question is, how to I get my controller to work for something like mydomain/brands/brand/12345 or something like that? When I try this currently, it says 404 error message.

Thanks in advance!

tadmin
  • 21
  • 1
  • 2

1 Answers1

1

Magento2 use same routing as in magento 1.

http://example.com/frontName/actionControllerName/actionMethod/

mydomain/brands/index/index handle by [Brands_Module_Root]/Controllers/Index/Index action.

You can pass parameters in request

mydomain/brands/brand/view/id/42 will be route to [Brands_Module_Root]/Controllers/Brand/View action.

In this action you can get parameters using request argument.

class View extends Action
{
    /**
     * {@inheritdoc}
     */
    public function execute()
    {
        $id = $this->getRequest()->getParam('id');

        // ...
    }
}

You can add custom router, if you need to use custom routing (mydomain/brands/brand/12345)

frontend/di.xml

<type name="Magento\Framework\App\RouterList">
    <arguments>
        <argument name="routerList" xsi:type="array">
            <item name="my-brands-router" xsi:type="array">
                <item name="class" xsi:type="string">Vendor\Brands\Controller\Router</item>
                <item name="disable" xsi:type="boolean">false</item>
                <item name="sortOrder" xsi:type="string">70</item>
            </item>
        </argument>
    </arguments>
</type>

Router.php

class Router implements \Magento\Framework\App\RouterInterface
{
    /**
     * {@inheritdoc}
     */
    public function match(\Magento\Framework\App\RequestInterface $request)
    {
        //@TODO implement router
    }
}

Look at app/code/Magento/Cms/Controller/Router.php for example.

Read more in official documentation

Max
  • 4,054
  • 17
  • 22