How to toggle column visibility in CGridView

Here is a nifty trick to share…

Let’s say you want to restrict the visibility of certain columns in a CGridView because the data may be sensitive.

So only users with a certain RBAC access level can see the data in the columns., and all others should not even see the columns.

(this way they don’t ask too many questions ;). )

If you set up your RBAC Permissions with a ‘reader’ role you can put this code in your view before you declare the grid.





//set $visible true if the user has reader RBAC permissions.

<?php $visible=Yii::app()->user->checkAccess("reader")? true : false; ?>


// now create a CGridView

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

	'id'=>'your-grid',

	'dataProvider'=>$dataProvider,

	'columns'=>array(

 	...

   // now create a column using the 'visible' CDataColumn property.

	array(

            	'name'=>'secret',

            	'value'=>'This is  a secret column  value. It won't be seen unless you have reader permission.',

            	'visible'=>$visible,

        	), 

 	...


	),

)); ?>



works great!

Nice tip. I have never explored much of CGridView & CListView features to put them into good use.

Will use it soon, thanks.

Thanks Nice tips.

You can also use like this.




// now create a CGridView

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

	'id'=>'your-grid',

	'dataProvider'=>$dataProvider,

	'columns'=>array(

 	...

   // now create a column using the 'visible' CDataColumn property.

	array(

            	'name'=>'secret',

            	'value'=>'This is  a secret column  value. It won't be seen unless you have reader permission.',

            	[b]'visible'=>Yii::app()->user->checkAccess("reader"),[/b]

        	), 

 	...


	),

)); ?>

thank you so muck, so great tip