Yii Tutorial on Yii GridView Widget

the gridview widget takes data from a data provider and presents data in the form of a table. each row of the table represents a single data item, and a column represents an attribute of the item.

step 1 − modify the datawidget view this way.

<?php
   use yii\grid\gridview;
   echo gridview::widget([
      'dataprovider' => $dataprovider,
   ]);
?>

step 2 − go to http://localhost:8080/index.php?r=site/data-widget, you will see a typical usage of the datagrid widget.

datagrid widget

the columns of the datagrid widget are configured in terms of the yii\grid\column class. it represents a model attribute and can be filtered and sorted.

step 3 − to add a custom column to the grid, modify the datawidget view this way.

<?php
   yii\grid\gridview;
   echo gridview::widget([
      'dataprovider' => $dataprovider,
      'columns' => [
         'id',
         [
            'class' => 'yii\grid\datacolumn', // can be omitted, as it is the default
            'label' => 'name and email',
            'value' => function ($data) {
               return $data->name . " writes from " . $data->email;
            },
         ],
      ],
   ]);
?>

step 4 − if you go to the address http://localhost:8080/index.php?r=site/data-widget, you will see the output as shown in the following image.

datagrid view

grid columns can be customized by using different column classes, like yii\grid\serialcolumn, yii\grid\actioncolumn, and yii\grid\checkboxcolumn.

step 5 − modify the datawidget view in the following way.

<?php
   use yii\grid\gridview;
   echo gridview::widget([
      'dataprovider' => $dataprovider,
      'columns' => [
         ['class' => 'yii\grid\serialcolumn'], 'name',
         ['class' => 'yii\grid\actioncolumn'],
         ['class' => 'yii\grid\checkboxcolumn'],
      ],
   ]);
?>

step 6 −go to http://localhost:8080/index.php?r=site/data-widget, you will see the following.

modified datagrid view