Friday, 24 April 2015

DropDown in filters instead of text boxes in Cgridview in YII

First of all,
We need to define methods in Model to generate options for Dropdown

Lets take a example GENDER, The gender can be male or female. This is simple example for drop down

Don't go for drop down if there are more than 10 options , which makes grid sluggish

Now, Lets assume we have field name "gender" in our model, so the methods defined in model are as follows

public static function getGenders( )
{
return array(
array('id'=>'','title'=>'Select'),
array('id'=>'M', 'title'=>'Male'),
array('id'=>'F', 'title'=>'Female'),
);
}
public static function getGender($onoff)
{
if($onoff == 'M')
return 'Male';
elseif($onoff == 'F')
return 'Female';
else
return $onoff;
/* elseif(($onoff == 'T')or($onoff == null))
return 'NIL'; */
}

There is no need to change or add any code in controller,

Now coming to view the admin.php consisting of CgridView at the columns definition

<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'demomodel-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
id,
name,
office,
array(
'name'=>'gender',
'header'=>'Gender', // This is displayed in grid only for heading purpose
'value'=>'Demomodel::getGender($data->gender)',
// Here getgender called for value to grid
'filter'=>CHtml::listData(Demomodel::getGenders(),'id','title'),
// Where as for Filters getGenders( ) is used.
),
array(
'class'=>'CButtonColumn',
),
),
)); ?>

Now the drop down displayed in place of textbox for filtering

No comments:

Post a Comment