Special $variables in CGridView and CListView

  1. CListView
  2. CGridView
  3. Passing your own variables

The popular [CListView] and [CGridView] widgets each take a data provider and iterate over each data object produced, calling the user's code to render each row one at a time, and most are familiar with the use of the $data variable to represent the current model object or array.

But there are additional special variables as well, including those that make their way all the way back to the calling controller, and this page means to reference them all.

CListView

The [CListView] widget calls your partial rendering _view on each item, setting these variables before calling each one:

  • $data - the current object or hash being rendered
  • $index - the zero-based index of the item being rendered (0, 1, 2, ...)
  • $this - the owner of the widget, usually the calling controller
  • $widget - the CListView widget itself

CGridView

The [CGridView] widget displays data in tabular form, and when each 'value' => '...' string is eval'd, these variables are available:

  • $data - the current object or hash being rendered
  • $row - the zero-based index of the item being rendered (0, 1, 2, ...)
  • $this - the [CGridColumn] object representing the column being rendered
  • $this->grid - the [CGridView] object that owns the column
  • $this->grid->owner - the owner of the grid, usually the calling controller

Passing your own variables

A very common request in the #yii channel is how to pass additional variables to the widget that are available by the rendering code. Though this is straightforward in CListView, it's not so simple in CGridView.

In CListView an additional viewData parameter can be passed to the widget as an array with additional variables:

$this->widget( 'zii.widgets.CListView', array(
    'dataProvider' => $dataProvider,
    'viewData' => array( 'switch' => true, 'blah' => 123 ),    // YOUR OWN VARIABLES
    'itemView' => '_view',
) );

Then, in the _view you can refer to $switch or $blah directly right alongside the other predefined variables.

For CGridView it appears that we have to extend the class to provide the variables in the widget. This extended class might look like:

// components/SpecialGridView.php
Yii::import('zii.widgets.grid.CGridView');

class SpecialGridView extends CGridView {
    public $extraparam;
}

and then called in the controller as:

// in your controller
  $this->widget('SpecialGridView', array(
    'dataProvider' => $dataProvider,
    'extraparam'   => 1234          // your special parameter
    'columns' => array( ... ),
  ) );

This done, the extra parameter is available in each the column as $this->grid->extraparam.

23 1
33 followers
Viewed: 78 052 times
Version: 1.1
Category: Tips
Written by: Steve Friedl
Last updated by: Steve Friedl
Created on: Oct 9, 2011
Last updated: 13 years ago
Update Article

Revisions

View all history

Related Articles