0

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?

2
  • not clear what you are asking, you have to specify the column names that you want to appear in the gridview, even if you want all or few of them only those will be rendered that are listed under columns option Commented Dec 2, 2018 at 15:50
  • @MuhammadOmerAslam 'col1' and 'col2' are in my query. for example my query is select col1,col2 from tbl_test , if I don't write columns name in column option of gridview, all columns of query will be displayed. I just want to add a checkbox column, because my columns name are dynamically changed, so I can't specify columns name. Commented Dec 3, 2018 at 7:36

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.