Passing Data from the Controller into a CGridView in Yii

Last updated:

Sometimes you need to send extra data from the controller into a field that can be evaluated as a PHP expression.

Example: (this is me adding custom buttons to a CGridView, as seen in this guide written by Trejder on how to customize button in a CGridView)

'class' => 'CButtonColumn',
    'template' => '{view}',
    'buttons' => [
        'view' => [
            'url' => 'Yii::app()->createUrl("/users/view",[\'id\'=>$data->id])',
        ],
        //....more code...

You can insert variables (like $data and $row and $this ) into strings that will be evaluated like PHP expressions like the one I've used for the url above.

If you ever want to be able to use an arbitrary variable in such expressions, this is what you need to do.

  • Create a subclass for CGridView

(in some place easy to find like /protected/extensions/MyCGridView.php)(you need that import at the top, by the way.)

    Yii::import('zii.widgets.grid.CGridView'); 
    class MyCGridView extends CGridView{
        public $myNewVariable;
    }
  • Create your new widget instead of the CGridView widget

(in your view)($someData is a variable you sent into the view from your controller)

    //some view code...
    <?php 
    $this->widget('coreWidgets.MyCGridView.MyCGridView', [
        'myNewVar'=>$someData,
        'columns'=>[
           'id',
           [
               'class' => 'CButtonColumn',
               'template' => '{view}',
               'buttons' => [
                   'view' => [
                       'url' => 'some_function($myNewVar)',
                   ],
               ] 
        //....more code... 

Dialogue & Discussion