Yii2,在rounte中的可选参数

问题描述:

在开发过程中,我遇到了urlManager的一个问题。Yii2,在rounte中的可选参数

我有SiteController与“类别”的行动。

public function actionCategory($id = null, $city = null, $location = null) 
{ 
    echo $id; 
    echo $city; 
    echo $location; 
} 

所有可能的组合,可以用这个动作来使用:

id, city, location = null 
id, city = null, location 
id, city = null, location = null 
id = null, city = null, location = null 
id = null, city = null, location 

我不知道怎么写的UrlManager的规则,后后,我会得到的变量以下值按链接:

<h4><?= Html::a('ID City', ['/site/category', 'id' => 'barbershop', 'city' => 'Praha'], ['class' => 'btn btn-primary']) ?></h4> 
The return value from "category" action: 

id = 'barbershop' 
city = 'Praha' 
location = '' 

<h4><?= Html::a('ID Location', ['/site/category', 'id' => 'barbershop', 'location' => '23,65'], ['class' => 'btn btn-primary']) ?></h4> 
The return value from "category" action: 

id = 'barbershop' 
city = '' 
location = '23,65' 

<h4><?= Html::a('ID', ['/site/category', 'id' => 'barbershop'], ['class' => 'btn btn-primary']) ?></h4> 
The return value from "category" action: 

id = 'barbershop' 
city = '' 
location = '' 

<h4><?= Html::a('City', ['/site/category', 'city' => 'Praha'], ['class' => 'btn btn-primary']) ?></h4> 
The return value from "category" action: 

id = '' 
city = 'Praha' 
location = '' 

<h4><?= Html::a('Location', ['/site/category', 'location' => '14,23'], ['class' => 'btn btn-primary']) ?></h4> 
The return value from "category" action: 

id = '' 
city = '' 
location = '14,23' 

你想你帮我解决这个问题吗?

根据您的要求,您只需要为控制器和操作名称设置规则。所有其他字段都通过$ _GET传递。你可以使用Yii::$app->getRequest()->getQueryParam('param')方法来获取它们。

对于你的网址,你可以使用正常的规则相当URL像

'urlManager' => [ 
     'enablePrettyUrl' => true, 
     'showScriptName' => false, 
     'rules' => [ 
      '<controller:\w+>/<id:\d+>' => '<controller>/view', 
      '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>', 
      '<controller:\w+>/<action:\w+>' => '<controller>/<action>', 
     ], 
    ],