How To Hide/show Columns In Cgridview Via Ajax

Hey guyz

I am kind of stuck right now. I have many columns for a grid. I want to give user an option that he can See only columns that he selected to show on runtime via Ajax

I know we use "$.fn.yiiGridView.update" to update grid on runtime but how can i update Grid to show/hide certain columns only.

  • (i did not have time to put code together, leave it to yourself)

try this:

  1. in your model, add

public static $visible_flag;

  1. in your view (gridView), add visible property to each of your column

'visible' => $model->visible_flag['field_name'],

  1. in between your view and model->search function, pass js version of this array when user select show and hide column before calling, in your search function reset $this->visible_flag before render ‘admin’ or ‘list’ page

** if you need persistence of the column selection, you may need using db or cookie trick, then each column’s visible property read such value from db or cookie

Dear Friend

This is quet intresting. Following is one simple implementation.

I have got a model.[b]User/b.


public function actionAdmin()


        $model=new User('search');

	$columns=array_keys($model->getAttributes());//we are getting in a array.array('id','name','age','sex','email','address'),


		$columns=$_GET["Columns"];//If user chooses the column, column names changes accordingly.

	$model->unsetAttributes();  // clear any default values










echo CHtml::checkBoxList('Columns',$columns,array_combine($columns,$columns),array('id'=>'columns','separator'=>''));



<?php $this->widget('zii.widgets.grid.CGridView', array(





)); ?>





                var data=$("input[name=\"Columns[]\"]:checked").serialize();





1.We are rendering a checkBoxList of attributes.By default I made all the checkboxes checked.

2.We are declaring columns inside the widget and merging with other columns.

3.We are registering a script to get the values from checkbox list and updating the grid with selected columns.

Here I made myself comfortable by calling attribute names as column.It becomes bit complex if you make a column

in an array format(name,value,type,etc).That also can easily be solved.

This is the screenshot from my localhost.




You can also set a class for each of the HTML elements and do a hide/show on the class:

I set this in some column definitions for the CGridView:





Thanks seenivasan And rootbear

I sorted that out with your suggestions :rolleyes: