Within my Yii 1.x application I am using the GridView widgets to display tabular data. I'd like to have a simple dropdown that will allow me to filter the results.
In this instance I have a set of 'Reward' data - each reward will either be 'Positive' OR 'Negative'. And I'd like to have a dropdown that will filter between the two.
Here is my code:
<?php $this->widget('bootstrap.widgets.TbGridView', array(
'dataProvider' => $model->search(true, $drill, isset($drillVal) ? $drillVal : false, isset($drillField) ? $drillField : false),
'filter' => $model,
'id' => get_class($model),
'type' => 'striped bordered condensed',
'template' => $model->getGridTemplate(),
'pagerCssClass' => 'pull-right pagination pagination-sm',
'columns' => array(
array(
'name' => 'reward_name',
'filter' => false
),
array(
'name' => 'reward_type',
'header' => 'Reward Type',
'filter' => false // need some code here for filtering
),
array(
'name' => 'totalPoints',
'header' => 'Total Points',
'filter' => false
),
),
));
For example this will look like the following....
+-----------------------------------------+
| Reward Name | Reward Type | Total Points|
+-----------------------------------------+
| Good Work | Positive | 500 |
| Great Effort| Positive | 150 |
| Naughty | Negative | -75 |
+-----------------------------------------+
I'd like the the filtering to allow me to show ONLY 'negatives' OR only 'positives'
Can anyone suggest how I best go about doing this?
Note - in my search() within the criteria element there is an IF statement as follows:
'IF(t.type="1","Deduction","Achievement") AS reward_type',
First, you need to have a dropdown list inside your view:
CHtml::dropDownList('rewardType', $rewardType, array(0 =>"-", 1=>"Positive", 2=>"Negative"), array(
'onchange' =>
"$.fn.yiiGridView.update('yourGridID(without # sign)',{ data:{rewardType: $(this).val() }})",
));
You can also use manual dropdown list(without yii) and send ajax request on onchange
event and update gridView on success event of ajax request.
Now you need to add this code inside your $model->search()
method(after initialize $criteria
):
if(isset($_POST['rewardType']) && ($_POST['rewardType'] != 0))
{
Yii::app()->session['rewardType'] = $_POST['rewardType'];
$criteria->addCondition("t.reward_type = ".$_POST['rewardType']);
}
And the final work is to adding one line at the beginning of your view file:
<?php $rewardType= (isset(Yii::app()->session['rewardType'])) ? Yii::app()->session['rewardType'] : 0; ?>
I have implemented similar situation recently. I had a dropdown list for changing page size inside CGridView and use this solution. Hope my solution can help you too.