Updated 1 month and 13 days ago
How to Add Advanced filters for Yii Grid
A grid is a series of vertical and horizontal lines that are used to subdivide a page vertically and horizontally into margins. All web applications will have grids in some form or the other, they will help us to filter the data and based on it do the necessary actions. Yii creates grids automatically if we use gii generator tool to generate CRUD. In this article we are showing how can we add advanced filters using chtml helper classes in Yii Grid.
Yii grid filters will get by default all column with text filters, but it is necessary to have more powerfull search options for user to get complex search results.
We can have multiple type of filters as listed below
Text Filed [By Default]
Dropdown Filter with static Data.
Dropdown filter with dynamic model data. [Relational Data]
Dropdown Filter using jquery multi select widget.
Text Field :- This will be default filter type which yii grid will give.Syntax:-
<?php $this->widget('zii.widgets.grid.CGridView', array( //your stuff 'filter'=>$model, 'columns'=>array( 'name', // by default text field is the filter ), )); ?>
Dropdown Filter with static Data:- Consider gender column in grid view, which will come default options 'Male','Female' so we don't need to have dropdown values dynamic. See following code to get dropdown filter with static values.
<?php ---- 'columns'=>array( array( 'name' =>'gender', //filter is dropdown - static data 'filter'=> array('M'=>'Male','F'=>'Female'), ), ----- ?>
Dropdown filter with dynamic model data: Considering updated user column in grid view, which will be foreign key relation with user model. So we need to display all user names in dropdown as filter. Following code will be example for this requirement.
<?php ---- , 'columns'=>array( array( 'name' =>'updatedby', //filter is dropdown with dynamic data 'filter'=> CHtml::listData(Users::model()->findAll(), 'user_id','Fullname'), ), ---- ?>
Dropdown Filter using jquery multi select widget: To add some more flexibility for filter data if we want to give dropdown with mulitselect and add more means providing jquery multi select where it will be easy to handle large set of data. It will not impact that much state forward to add like above filters first we need to .