Rahman
Rahman

Reputation: 452

How to add a checkbox column to existing gridview columns in yii2?

I want to add a column to gridview but I don't want to list all of columns(because there are some columns as default). I know that I can add a column by follow:

$widget = Yii::createObject([
    'class' => 'yii\grid\GridView',
    'dataProvider' => $dataProvider,
    'columns' => [
        'col1',
        'col2',
        'class' => 'yii\grid\CheckboxColumn',
    ]
]);

but I don't want to list all default columns and just add a checkbox column. like follow:

$widget = Yii::createObject([
    'class' => 'yii\grid\GridView',
    'dataProvider' => $dataProvider,
    'columns' => [
        'class' => 'yii\grid\CheckboxColumn',
    ]
]);

Then it will be displayed at the end of default columns. How can I do it?

Upvotes: 0

Views: 591

Answers (1)

Luna
Luna

Reputation: 2322

The yii framework does not support this need. We can do this in other ways.

The first: get all your column names and insert the checkbox column before displaying the list

$query = DataModel::find()->select('...')->asArray();

$columns = array_keys($query->one()); // if you know that all column names can also be assigned directly without dynamic acquisition
array_unshift(['class' => \yii\grid\CheckboxColumn::class], $columns);

$widget = Yii::createObject([
    'class' => 'yii\grid\GridView',
    'dataProvider' => new \yii\data\ActiveDataProvider([
        'query' => $query,
    ]),
    'columns' => $columns,
]);

]);

Second: extend the yii\grid\GridView::initColumns() method of the yii framework. e.g:

class MyGridView extends \yii\grid\GridView {
    public $expandColumns = [];

    protected function initColumns() {
        parent::initColumns();
        \yii\helpers\ArrayHelper::merge($this->columns, $this->expandColumns);
    }
}

// in view
$widget = Yii::createObject([
    'class' => MyGridView::class,
    'dataProvider' => $dataProvider,
    'expandColumns' => [
        [
            'class' => \yii\grid\CheckboxColumn::class,
        ],
    ]
]);

Answer translation from Google Translate, hope to help you.

Upvotes: 1

Related Questions