Yii: CGridView Filter examples

Last updated:

In order to able to use filters in a CGridView inside a Yii application, this is what you need to do:

on the model, you need a search() method (maybe you already have one, if you used Gii)

public function search() {
    $criteria = new CDbCriteria;
    $criteria->compare('id', $this->id);
    $criteria->compare('name', $this->name, true);
    * ------now the data provider---------
    return new CActiveDataProvider($this, array(
                'criteria' => $criteria,
                'pagination' => array(
                    'pageSize' => 20,

in the controller, this is the code you need(replace actionIndex, YourModelClassName with your specific values):

public function actionIndex() {
    $model = new YourModelClassName('search');
    $model->unsetAttributes();  // clear any default values
    $this->render('index', array(

on the view file: (where you actually instantiate the CGridView):

<?php $this->widget('zii.widgets.grid.CGridView', array(

If you want look at how to make filters with related models, you might want to have a look at this: yii-cheat-sheet-filtering-by-related-models-in-a-cgridview

N.B.: another good source of example on how to make filters are the admin view files that are generated by Gii.

This is a w.i.p. (work in progress).

Dialogue & Discussion