Yii CGridView Example on Using CCheckBoxColumn

Yii CGridView Example on Using CCheckBoxColumn

Last updated:

Say you have a CGridView widget that you created like this (assuming you've passed a suitable data provider from your controller in variable $dp (like an instance of CActiveDataProvider)):

In this example, the models in the data provider are objects which have id and name attributes:

$this->widget('zii.widgets.grid.CGridView',[
    'id' => 'my-grid',
    'dataProvider' => $dp,
    'selectableRows'=>5, // can be anything other than 1 or 0
    'columns' => [
        [
            'name' => 'id'
        ],
        [
            'name' => 'name'
        ],
        [
            'header' => "foo",
            'class' => 'CCheckBoxColumn',
            'selectableRows' => null,
            'checked' => '($data->name !== "john")',//php code in single quotes
        ]
    ]
]);

Heads-up

  • Selections across pages

No, selections aren't kept across pages so, if you paginate away from the current page, your selections are lost. Like most things on the internet, someone has already come across that problem and solved it: I use SelGridView Yii Extension and it works great.

  • Using Javascript to get Checked rows in a grid

There's actually a jquery function that's built into Yii jquery code that allows you to get selected rows: $.fn.yiiGridView.getSelection('my-grid'). Note that I said selected rows. To make checkboxes cause the underlying rows to get selected, you just need to make attribute "selectableRows" in the grid be something other than 0 or 1 and attribute "selectableRows" (yes they have the same name) in the column be null, and thenjust use the method above to get all selected rows.

Dialogue & Discussion