GridView widget is used to display data records with such features like pagination, sorting and filtering.
For GridView widget a data provider should be set.
$dataProvider = new ActiveDataProvider([
'query' => Post::find(),
'pagination' => [
'pageSize' => 20,
],
]);
Show the widget:
echo GridView::widget([
'dataProvider' => $dataProvider,
]);
Columns
The columns of the grid table are configured in terms of yii\grid\Column classes,
which are configured in the columns property of GridView configuration.
echo GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
//...
],
]);
The default class is yii\grid\DataColumn, which represents a model attribute
and can be sorted and filtered by.
Examples:
'columns' => [
'id',
'username',
'email',
]
'columns' => [
[
'class' => 'yii\grid\DataColumn', // can be omitted, as it is the default
'value' => function ($data) {
return $data->name; // $data['name'] for array data, e.g. using SqlDataProvider.
},
],
]
'columns' => [
[
'label' => 'Name', // Label for the column.
'value' => function ($data) {
return $data->name;
},
],
]
// Just change the label:
'columns' => [
[
'label' => 'Name',
'attribute' => 'name',
],
]
'columns' => [
['class' => 'yii\grid\SerialColumn'], // Class that generates serial numbers.
]
'columns' => [
['class' => 'yii\grid\CheckboxColumn'], // Class that generates serial numbers.
]
// Returning value will be HTML encoded. So we need to specify `raw` format to skip it:
[
'label' => 'Link',
'format' => 'raw',
'value' => function($model) {
return "<a href=" . Html::encode($model->link) . " class='btn btn-default' target='_blank'><span class='glyphicon glyphicon-link'></span></a>";
},
],
// If we want to hide a column using some condition:
[
'label' => 'Score',
'attribute' => 'score',
'visible' => $this->context->action->id == 'starred',
],
// Adding a class to the cell:
[
'attribute' => 'score',
'contentOptions' => function ($model, $key, $index, $column) {
return ['class' => 'maker-cell'];
},
],
Styles
Styles for the table:
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,,
'tableOptions' => [
'class' => 'table table-striped table-bordered'
],
...
Change a column width:
[
'attribute' => 'score',
'headerOptions' => ['width' => '80'],
],
Changing layouts
To hide the pagination section:
// Default value:
'layout' => "{summary}\n{items}\n{pager}",
// Without pagination:
'layout' => "{summary}\n{items}",
Andrew Dorokhov