Update Gridview with Dropdown Selection

I recently worked on updating the content of a gridview based on the selection of a dropdown menu. I thought I should share it in the forum...

In the view you have:

  1. the js script for capturing the onchange of the select:
Yii::app()->clientScript->registerScript('sel_status', "
        $('#selStatus').change(function() {
            //alert(this.value);
            $.fn.yiiGridView.update('milestone-category-grid', {
                    data: $(this).serialize()
            });            
            return false;
        });
    ");
  1. the code for the select:
$data = CHtml::listData(Status::model()->findAll('IsProcess=?',array(1)), 'ID', 'Description');

$select = key($data);

echo CHtml::dropDownList(
    'dropDownStatus',
    $select,            // selected item from the $data
    $data,       
    array(
        'style'=>'margin-bottom:10px;',
        'id'=>'selStatus',
    )
);
  1. the code for the gridview widget:
$this->widget('bootstrap.widgets.TbGridView',array(
	'id'=>'milestone-category-grid',
	'afterAjaxUpdate' => 'installSortable',
	'enableSorting' => false,
	'dataProvider'=>$model->search($select),
	'rowCssClassExpression'=>'"items[]_{$data->ID}"',
	'columns'=>array(
		'Description',
	),
)); ?>
  1. In the "Search" function of your corresponding model the following code needs to capture the GET variable that is being passed, in my case it is 'dropDownStatus', the name given to the select (use Firebug, if necessary, to get the name of the variable being passed):
public function search($status=false)
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		if ($status!==false) {
			$criteria->condition='StatusID=:StatusID';
			$criteria->params=array('StatusID'=>$status);
		}

		if (isset($_GET['dropDownStatus'])) {
			$criteria->condition='StatusID=:StatusID';
			$criteria->params=array('StatusID'=>$_GET['dropDownStatus']);
			$criteria->order='Position ASC';
		}

...


With this you have a select and a gridview that updates dynamically, without using ajax.

Feedback welcome...

0 0
4 followers
Viewed: 16 913 times
Version: 1.1
Category: Tips
Written by: lgastmans
Last updated by: lgastmans
Created on: Apr 22, 2014
Last updated: 9 years ago
Update Article

Revisions

View all history

Related Articles