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 we point to http://hostname/basic/web/news/items-list
without specifying the year or category parameter, the first rule will be skipped and the second one will be executed using shopping as the default value, because the category is missing.
Now, create an index page to see how to create these custom URLs. In this page, we will display URL links to have the data filtered by year (for the last 5 years) and links to view the data filtered by category (shopping and business).
URLs are made using yiihelpersUrl
, along with the to()
method, where the first parameter can be:
The first parameter can be:
toRoute()
method to generate the URL. The first item of this array is the route to be rendered and the other items are the parameters to be passed to the route; for example, Url::to(['news/items-list', 'year' => 2015])
.@
; this is treated as an alias, and the corresponding aliased string will be returnedCreate a simple actionIndex
in NewsController
:
public function actionIndex() { return $this->render('index'); }
Then, create a view for the index action under views/news/index.php
:
<?php use yiihelpersUrl; use yiihelpersHtml; ?> <b>Filter data by year:</b> <br /> <ul> <?php $currentYear = date('Y'); ?> <?php for($year=$currentYear;$year>($currentYear-5);$year--) { ?> <li><?php echo Html::a( 'List items by year '.$year, Url::to(['news/items-list', 'year' => $year]) ) ?></li> <?php } ?> </ul> <br /> <b>Filter data by category:</b> <br /> <ul> <?php $categories = ['business', 'shopping']; ?> <?php foreach($categories as $category) { ?> <li><?php echo Html::a( 'List items by category '.$category, Url::to(['news/items-list', 'category' => $category]) ) ?></li> <?php } ?> </ul> <br /><br />
Point to http://hostname/news/index
and it will display:
18.220.178.207