Yii 1.1: Clear CGridView Filters, Sort & Pager


Clearing CGridView filters and sort orders from the web pages, is usefull for the end user. Yii does not seem to propose a standard method. Furthermore, this is especially usefull when filters are "remembered" in the user's session.

To remember filters, I use ERememberFiltersBehavior and a previous wiki also shows a method to remember filters.

Prior to developing an method, I looked at what existed already. To clear filters, EButtonColumnWithClearFilters supposedly does the job, and a web page / forum entry also explain a method.

They did not meet my "requirements", so I worked out another method.

The code is not perfect yet (I would like to not use 'window.location.href'), but I thought sharing this is usefull for you. If you work out a better way, share it here!

The code basically goes like this:

// The usual pre-initialisation code for a CGridView.
$model=new MyModel('search');  // Code to set filters not shown.
$gridId='gridId'; // Id of the grid
$dataProvider=$model->search(); // Setup of data provider, may be more complex.
// Determine the JavaScript to reset the filters.
// 'window.location.href' should be improved upon but is ok in most cases.
                'data' => array(
                        get_class($model) . '[]' => '',
                        $dataProvider->sort->sortVar => ' ',
                        $dataProvider->pagination->pageVar => 1 
                'url' => new CJavaScriptExpression('window.location.href') 
$jsClear=new CJavaScriptExpression("jQuery('#$gridId').yiiGridView('update',$clearFilterData);");
$this->widget('zii.widgets.grid.CGridView', array(

The resulting JavaScript code looks like this, in case you want to write it more directly:

jQuery('#gridId').yiiGridView('update',{data:{'MyModel[]':'','MyModel_sort':' ','MyModel_page':1},'url':window.location.href})

This seems less complex and more flexible than the other code I have seen. It also uses the actual sortVar and pageVar values (rather than supposing that they use the Model class name).

You can use the '$jsClear' JavaScript code any way you like (in the above, I use it to define a link (used in the CGridView header here), and to make the CButtonColumn filter zone clickable.

By setting the 'clearFilter' class on the 'filter' area of the CButtonColumn, you can suggest the clear filter function by attaching a background to it in your CSS.

Be the first person to leave a comment

Please to leave your comment.

Write new article