Special $variables in CGridView and CListView

You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#4) »

  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.


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


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. Unfortunately, it's not so simple as it looks, so unless the variable is readily available in the controller (reachable by $this in CListView or $this->grid->owner in CGridView), you pretty much have to extend the classes to do this.

Extending CListView might look like:

// components/SpecialListView.php

class SpecialListView extends CListView {
    public $extraparam;

and then called in the controller as:

// in your controller
  $this->widget('SpecialListView', array(
    'dataProvider' => $dataProvider,
    'itemView'     => '_view',      // partial rendering
    'extraparam'   => 1234          // your special parameter
  ) );

This done, the extra parameter is available in the _view as $widget->extraparam.

For CGridView it will be likewise, using $this->grid->extraparam from within each column to get at the parameter.

23 1
Viewed: 77 410 times
Version: Unknown (update)
Category: Tips
Written by: Steve Friedl
Last updated by: Steve Friedl
Created on: Oct 9, 2011
Last updated: 12 years ago
Update Article


View all history

Related Articles