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 $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(1 => 'Male', 2 => 'Female'),
        ),
        array(
            'class' => 'CButtonColumn',
        ),
    )
);
?>

Note lines 9 to 12 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:

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:

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

9 thoughts on “Yii: drop down list filter in CGridView

  1. Piotr Reply

    How can I do the same but with array defined in model ??

  2. Ali Reply

    this is a ** bleep ** example.
    Doesnt help in anyway.
    if u r to write .. write something useful to share with the community.

  3. prettyscripts Reply

    @ali, your profane language has been edited out. if you do not find it helpful it’s appreciated constructive feedback for improvement.

  4. Pablo Reply

    If I’m not wrong, the filter should be
    ‘filter’ => Code::model()->getCodeArray()

    Thanks for the post, Pablo.

  5. Alex Reply

    No need of extra getCodeArray() method. Can be much simplier:
    ‘filter’ => CHtml::listData(Code::model()->findAll(), ‘id’, ‘code’)

  6. The Schaef Reply

    Pablo’s response is correct.

    e.g. Alex, while it may be true that a method for the options isn’t strictly necessary just to add a dropdown to the cGridView filter, but when I have records that I want to constrain to only a few select choices, especially with foreign key constraints on related tables, I am already creating these methods to allow people to select from a specific list of options when they are creating/updating/searching records. So this is a great way for me to take the same work already done once, and apply it to the admin page for simpler filtering.

Leave a Reply

Your email address will not be published. Required fields are marked *