2017-10-19 32 views
0

Au cours du développement, j'ai fait face à un problème avec urlManager.Yii2, paramètre facultatif dans le rounte

J'ai SiteController avec l'action "catégorie".

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

Toutes les combinaisons possibles qui peuvent être utilisés avec cette action:

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

Je ne sais pas comment écrire les règles du urlManager, après que je vais obtenir les valeurs suivantes dans les variables après appuyez sur les liens:

<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' 

Voulez-vous m'aider avec ce problème?

Répondre

0

Selon vos besoins, vous devez définir des règles uniquement pour le nom du contrôleur et de l'action. Tous les autres champs sont passés par $ _GET. et vous pouvez les récupérer en utilisant la méthode Yii::$app->getRequest()->getQueryParam('param').

Pour vous URL, vous pouvez utiliser des règles normales pour l'URL jolie comme

'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>', 
     ], 
    ],