Search code examples
yiicontrolleryii2rulesyii-url-manager

Yii2, optional parameter in the rounte


During the development, I have faced to the one issue with urlManager.

I have SiteController with "category" action.

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

All possible combination that can be used with this 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

I do not know how to write the rules in the UrlManager, after that I will get the following values in the variables after press the links:

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

Would you like you help me with this issue?


Solution

  • As per your requirements you need to set rules only for Controller and action name. All other fields are passed through $_GET. and you can fetch them using Yii::$app->getRequest()->getQueryParam('param') method.

    For you url you can use normal rules for pretty url like

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