Yii2 - Url Manager - Specific rule failing

397 Views Asked by At

I have the following url:

http://example.com/user/login

If I input the url in the browser, it matches de rule:

'<module:user>/<slug:[\w\-]+>' => '<module>/<slug>'

If I create the url:

Yii::$app->urlManager->createAbsoluteUrl(["user/index", "slug" => "login"]);

It should create the same url as above but instead it creates:

http://example.com/user/index?slug=login

But If I change the rule to:

'<module:user>/<slug:[\w\-]+>' => '<module>/index'

It works ok, any ideas why? I guess for some reason:

  1. It is passing slug empty to or
  2. It is an invalid value.

Any ideas?

1

There are 1 best solutions below

4
rob006 On

That is because slug is part of the route pattern: '<module>/<slug>'. So <slug:[\w\-]+> is not treated as a named GET param, but as a part of the route. That means that URL /user/something will point to route user/something without any GET params.

You should not use the same name for route patterns and named params. You should either use different name:

'<module:user>/<action:[\w\-]+>/<slug:[\w\-]+>' => '<module>/<action>'

Or hardcode action for specified rule (as you already did in second example):

'<module:user>/<slug:[\w\-]+>' => '<module>/index'

Note that this will also match standard actions, like user/view.