0

I want to generate URL's that can handle multiple parameters. Eg:

    www.example.com/product/index?brand=brand-name,
    www.example.com/product/index?category=category-name,

I want the url be like :

   www.example.com/brand-name,
   www.example.com/category-name

Tried some url rules,but it doesn't work.

'rules' => [
       [
        'pattern' => '<brand:\w+(-\w+)*>/<category:\w+(-\w+)*>',
        'route' => 'product/index',
        'defaults' => [
                   'brand' => null,
                   'category' => null,
              ]
      ]
]

This is my reference :

Reference question

  • If either have to add some way at the target action to tell if given name is category or brand or to make these two urls explicitly different (like with prefix or something). – Bizley Jun 27 '19 at 06:26
  • Is there any other way to handle with same action? I tried the above rule, but it not working with two parameter – SaabzCoder Jun 27 '19 at 06:33
  • The problem is how the system should know that if you enter `www.example.com/abc` `abc` is brand and not a category or other way around. – Bizley Jun 27 '19 at 07:21

1 Answers1

0

To do this you will have to stick to the prefixed version. So the brand param should always be prefixed with brand- and the category always with category-. Otherwise there is no way to tell what is what.

Add the following rules. This will put everything that matches brand-\w+ in the brand argument and pass it to product/index. Same for category.

'<brand:brand-\w+>' => 'product/index',
'<category:category-\w+>' => 'product/index',

To see that it works

public function actionIndex($brand = null, $category = null) {
    echo "Brand: $brand<br />";
    echo "Category: $category<br />";

    echo Url::toRoute(['dev/index', 'brand' => 'brand-name']) . '<br />';
    echo Url::toRoute(['dev/index', 'category' => 'category-name']) . '<br />';
}
Jap Mul
  • 17,398
  • 5
  • 55
  • 66