Yii 2 Optional Parameter

php, yii, yii-url-manager, yii2

Solution

This is not very clear in the documentation (see http://www.yiiframework.com/doc-2.0/guide-runtime-routing.html), but here is the answer:

By default, all parameters declared in a rule are required. If a requested URL does not contain a particular parameter, or if a URL is being created without a particular parameter, the rule will not apply. To make some of the parameters optional, you can configure the defaults property of a rule. Parameters listed in this property are optional and will take the specified values when they are not provided.

So your route must be expressed like:

array(
  'pattern' => '<controller:\w+>/<action:\w+>/<status>',
  'route' => '<controller>/<action>',
  'defaults' => array('status' => '<a default value for status>')
)

Problem

Ok, I am transitioning an app from yii 1.1 to yii 2, unfortunately I cannot figure out how to use optional parameters within my url routes. Even when I set defaults in the urlmanager in config I can't state the second parameter without the first one or I end up with a 404 error. Is there a way to replicate optional url parameter rules such as ``` array( '<controller:\w+>/<action:\w+>?(/<status>)?', 'pattern' => '<controller>/<action>' ), ``` in yii 2 ?

Original source

Related problems