Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 routing - pass parameter to route in rules

When a user accesses domain/page, I need to route them to controller/action/100. I don't want to pass any parameter through the URL, but want to add it in url rules.

I added the code below to my config file.

'urlManager' => [
    'rules' => [
        'login' => 'site/login',  // working
        'about' => 'cms/page/10'  // Not Working
        'about' => 'cms/page?id=10'  // Not Working
    ],
],

The first rule is working fine.

Can I pass the parameter for the route in url rules?

like image 685
suneeth Avatar asked Apr 27 '16 09:04

suneeth


1 Answers

You need to use defaults and declare the rule explicitly:

'urlManager' => [            
    'rules' => [
        'login' => 'site/login',
        [
            'pattern'  => 'about', 
            'route'    => 'cms/page',
            'defaults' => ['id' => 10],
        ]  
    ],
],

Add 'mode' => \yii\web\UrlRule::PARSING_ONLY to this rule if you want to prevent the transformation when you create a URL with the UrlManager (e.g. Url::to() uses the UrlManager and its rules and works in the opposite direction, that is Url::to(['cms/page', 'id' => 10]) will generate a link about)

Also consider to configure a redirect at your web server instead.

like image 51
robsch Avatar answered Sep 18 '22 19:09

robsch