Hide CButtonColumn of CGridView if not admin

Hi there,

I’m a newcomer to Yii and have searched around for quite some time trying to find how to hide the CButtonColumn of a CGridView if the logged in user is not admin.

What’s the best way to go about it?

I basically want to run this code if user is admin…


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

        'id'=>'result-grid',

        'dataProvider'=>$dataProvider,

        'filter'=>$model,

        'columns'=>array(

            'datePlayedFormatted:text:Date Played',

            'winner.fullName:text:Winner',

            'matchResultText:text:Match Result',

            'loser.fullName:text:Loser',

            'gameScores:text',

            array(

                'class'=>'CButtonColumn',

            ),        

        ),

    ));

…and this code otherwise (i.e. ommitting the column which allows you to act on individual rows)…


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

        'id'=>'result-grid',

        'dataProvider'=>$dataProvider,

        'filter'=>$model,

        'columns'=>array(

            'datePlayedFormatted:text:Date Played',

            'winner.fullName:text:Winner',

            'matchResultText:text:Match Result',

            'loser.fullName:text:Loser',

            'gameScores:text',

        ),

    ));

Ideally I’d like to know the best practice recommendation for this kind of thing, rather than a quick and dirty non-standard solution.

Any advice would be much appreciated.

http://www.yiiframework.com/doc/api/1.1/CGridColumn#visible-detail




array(

  'class'=>'CButtonColumn',

  'visible'=>'Yii::app()->user->isAdmin()',

);



Something along those lines should work

The “visible” property is evaluated for every row so it’s good to use only if you need to display/hide “data” from row to row depending on some row value…

Check this post for a better solution - http://www.yiiframew…dpost__p__46410

Many thanks to both of you for your alternative suggestions for achieving the same outcome. Given mdomba’s comment about the visible property being evaluated for every row I’ve gone with the following code…


$columns[]='datePlayedFormatted:text:Date Played';

$columns[]='winner.fullName:text:Winner';

$columns[]='matchResultText:text:Match Result';

$columns[]='loser.fullName:text:Loser';

$columns[]='gameScores:text';

if ($isAdmin) {

    $columns[]=array(

        'class'=>'CButtonColumn',     

    );

}

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

    'id'=>'result-grid',

    'dataProvider'=>$dataProvider,

    'filter'=>$model,

    'columns'=>$columns,

));