What would be the Urlmanager rule for changing a url like site/product?name=[name] to product/[name]?
I tried
'<action:\w+>' => 'site/<action>',
'product/<id:\d+>' => 'product',
But it gives me a 404
Before answering to your question a short explain what is wrong.
You try to pass alpha chars to an action that handles only integers.
The rule 'product/<id:\d+>'
indicate that the url should be like:
product/1
product/777
product/8888
The regular expression \d+
limits this url part to an integer.
Answer
For url like product/[name]
, you should add this pattern:
//...
'product/<name:[\w]+>' => 'product/item',
//...
Where 'product/<name:[\w]+>'
will match any url like:
product/any
product/alpha
product/productname
The <name:[\w]+>
will be the parameter that will hold matched url part and and creates a variable named $name
that will contain only the alpha chars, due the regular expression [\w]+
. This variable will be passed to controller action.
And 'product/item'
is the controller / action that will handle request, in this example is ProductController
and actionItem
with parameter $name
.
Now in ProductController you need to add an action:
//...
/**
* Handle products by name
* @param string $name
*/
public function actionItem($name) {
// ... do stuff here
}
//...
More information can be found here Yii2 Routing and URL Creation.