Configuring widget defaults
In Yii, code pieces commonly used in views are placed into widgets. For example, a widget can render a tag cloud or provide a custom form input type. Core widgets are highly configurable and are used in views as follows:
<?$this->widget('CLinkPager', array( 'pages' => $pages, 'pageSize' => 15, ))?>
In the preceding code, we are using $this->widget
that calls a CLinkPager
widget with an array of parameters to display a pagination. pages
and pageSize
are both assigned to the corresponding public properties of CLinkPager
before it is being rendered.
Note that we have changed the count of items per page to 15 in our example. If we want our pagination to display 15 items per page on all pages of our application, then we will need to provide a pageSize
parameter with value 15 for all CLinkPager
widget calls. Is there a better way? Definitely, yes.
How to do it…
A Yii web application provides a bunch of components. One of them is a widget factory that since Yii 1.1.3 can be used to set widget defaults.
- Let's use it to set
pageSize
application-wide. We will need to edit the application configuration filemain.php
as follows:return array( … 'components'=>array( 'widgetFactory'=>array( 'widgets'=>array( 'CLinkPager'=>array( 'pageSize'=>15, ), … ), ), … ), );
- Now, the default value for
CLinkPager
'spageSize
will be 15, so if we omit this parameter for all the applicationCLinkPager
s then it will be 15, application-wide. - Moreover, we still can override the
pageSize
value for a specific widget:<?$this->widget('CLinkPager', array( 'pages' => $pages, 'pageSize' => 5, ))?>
This works much like the CSS cascade. You are setting the default overall style in an external file, but are still able to override this through inline styles for individual widgets.
See also
- The recipe named Configuring components in this chapter