Thursday, March 15, 2012

yii: drop down list filter in CGridView

BY default the filter for each data column is a text field. to display the field as drop down list, CDataColumn::filter property must be set as an array.

for example, for user table there's column for sex represented by 1 = male and 2 = female. in the view file:

PHP:
<?php 
$this->widget('zii.widgets.grid.CGridView'array(
    'id'=>'user-grid',
    'dataProvider' => $model->search(),
    'filter' => $model,
    'columns' => array(
        'id',
        'name',
        'email',
        array(
            'name' => 'sex',
            'filter' => array(=> 'Male'=> 'Female'),
        ),
        array(
            'class' => 'CButtonColumn',
        ),
    )
);
 ?>

note lines 10 to 13 from the above code.

note for the array data: the array index is used for value attribute in <option> tag, and the array value is the display text.

data from a model


say if a model has attributes id and code, and you want to list codes in drop down list.

in model, define a method to return array of data:

PHP:
class Code extends CActiveRecord {
...
    public function getCodeArray() {
        $codes self::model()->findAll();
        $data array(); // data to be returned
        foreach ($codes as $c) {
            $data[$c->id] = $c->code;
        }
        return $data;
    }
...
}

in view file, replace filter of the column with the following code:

PHP:
...
    'filter' => Code->getCodeArray(),
...

No comments:

Post a Comment