Get Parameters Problems in Yii2

398 views Asked by At

My question is that i will have the ? at the beginning of the get parameter's name.For example, if the url is

https://example.com/path?id=2

I will get a get parameter named ?id.How can I get the id without ? instead of using such way:

https://example.com/path?&id=2

It's wired : )

---------------- Here is details ----------------

The url manager config:

[
    'urlManager' => [
        'enablePrettyUrl'   => true,
        'showScriptName'    => false,
        'rules' => [
            [
                'pattern'   => '<lang:(zh|en)>/login',
                'route'     => 'account/default/login',
            ],
            [
                'pattern'   => '<lang:(zh|en|api)>/<modules>/<controller>/<action>',
                'route'     => '<modules>/<controller>/<action>',
                'defaults'  => [
                    'lang'      => 'zh',
                    'modules'   => 'dashboard',
                    'controller'=> 'default',
                    'action'    => 'index',
                ],
            ],
        ],
    ],
];

You see, I will use the lang parameter to control the language version of the website.And I found Yii will handle the lang as a get parameter.So that's the problem.lang might be the first get parameter, so the php handle the the ? as the part of the parameter's name.

if I print the get parameters, I will get this.

https://example.com/en/modules/controller/action?id=1

The code goes:

var_dump(\Yii::$app->request->get());

It will print:

array(2) { ["lang"]=> string(3) "en" ["?id"]=> string(1) "1" }

THX A LOT.

1

There are 1 answers

3
Raul Sauco On

Include the ID parameter in the pattern that you are matching against.

[
    'urlManager' => [
        'enablePrettyUrl'   => true,
        'showScriptName'    => false,
        'rules' => [
            [
                'pattern'   => '<lang:(zh|en)>/login',
                'route'     => 'account/default/login',
            ],
            [
                // Add the id to the pattern in the following line
                'pattern'   => '<lang:(zh|en|api)>/<modules>/<controller>/<action>/<id:\d+>',
                'route'     => '<modules>/<controller>/<action>',
                'defaults'  => [
                    'lang'      => 'zh',
                    'modules'   => 'dashboard',
                    'controller'=> 'default',
                    'action'    => 'index',
                ],
            ],
        ],
    ],
];

Changing the pattern element to the following:

'pattern' => '<lang:(zh|en|api)>/<modules>/<controller>/<action>/<id:\d+>',

Will capture a digit after a slash and make it available to your action as the $id method parameter.

If you wanted to use a question mark, instead of a slash, to separate the action from the parameter, I guess you could use this pattern:

'pattern' => '<lang:(zh|en|api)>/<modules>/<controller>/<action>?<id:\d+>'

But I have not tried it.