Default parameters in rules

In rules, all the parameters that are declared are required; if the URL misses some parameter, the rule will not be applied. This problem can be solved using the default property of rule.

The URL rule structure has a parameter, named defaults, containing default parameters to be passed as default. Parameter defaults is an array, where keys are names of parameters and values are their corresponding values.

For example, change the second rule to a complete array and add ['category' => 'shopping'] as the default property rule:

'rules' => [
    'news/<year:\d{4}>/items-list' => 'news/items-list',
    [
        'pattern' => 'news/<category:\w+>/items-list',
        'route' => 'news/items-list',
        'defaults' => ['category' => 'shopping']
    ]
],

Now, if ...

Get Yii2 By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.