Yii Framework 2 : Gridview

In yiiframework 2.0, The gridview widget is used to display the data like image, text, etc in a grid. It is having a lot features like sorting, pagination, filtering, styling etc. This widgets is mostly used by developers. I added some properties for this

Sample Category GridView

I generated this gridview widget using CRUD for category table in yiiframework 2.0.


<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'categoryid',
        'categoryname',
        'parentid',
        'createdon',
        // 'isactive',
        ['class' => 'yii\grid\ActionColumn'],
    ],
]);
?>

Gridview Options

By default the gridview ‘div’ is having the ‘grid-view’ class. If we want, we can edit this class using ‘options’.


<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        //.........
        ['class' => 'yii\grid\ActionColumn'],
    ],
    'options'=>['class'=>'grid-view gridview-newclass'],
]); 
?>

Table Options

By default the grid view table is having the ‘table table-striped table-bordered’ class. We can change or add class, style etc using ‘tableOptions’ of gridview yiiframwork2.0


<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        //.........
        ['class' => 'yii\grid\ActionColumn'],
    ],
    'tableOptions' =>['class' => 'table table-striped table-bordered'],
]);
?>

Table Row Options

We can add class, style etc for table row using ‘rowOptions’.


<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        //.........
        ['class' => 'yii\grid\ActionColumn'],
    ],
    'rowOptions'=>function ($model, $key, $index, $grid){
        $class=$index%2?'odd':'even';
        return array('key'=>$key,'index'=>$index,'class'=>$class);
    },
]);
?>

Gridview Layout Format

By default, the gridview layout is containing ‘summary’,’items’,’pager’. If we want, we can add/change this layout using ‘layout’ properties of yii2.0.
Yii2


<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'layout'=>"{sorter}\n{pager}\n{summary}\n{items}",
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        //.........
        ['class' => 'yii\grid\ActionColumn'],
    ],
]); 
?>

Show/Hide the summary text, footer and header of gridview table yii2.0.


<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'summary'=>'',
    'showFooter'=>true,
    'showHeader' => true,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        //.........
        ['class' => 'yii\grid\ActionColumn'],
    ],
]);
?>

Show/Hide GridView On Empty

Hide the gridview using ‘showOnEmpty’ properties If the data is not available to show in gridview table.
Yii2 Gridview Show Hide On Empty


<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'showOnEmpty'=>true,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        //.........
        ['class' => 'yii\grid\ActionColumn'],
    ],
]); 
?>

Fill Empty Cell By Value


<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'emptyCell'=>'-',
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        //.........
        ['class' => 'yii\grid\ActionColumn'],
    ],
]); 
?>

GridView Button Template And Properties

Every developer would like to play with gridview action. I added the code for that from my experience.

Template, Header, HeaderOptions

Configure the gridview button or template, header lable value and button options like class, style etc.


<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        //.........
        [
            'class' => 'yii\grid\ActionColumn',
            'header'=>'Action', 
            'headerOptions' => ['width' => '80'],
            'template' => '{view} {update} {delete}{link}',
        ],
    ],
]); 
?>
New Button

Add the new button in gridview action template and configure the url, text, title etc.


<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        //.........
        [
            'class' => 'yii\grid\ActionColumn',
            'template' => '{view} {update} {delete} {link}',
            'buttons' => [
                'update' => function ($url,$model) {
                    return Html::a(
                        '<span class="glyphicon glyphicon-user"></span>', 
                        $url);
                },
                'link' => function ($url,$model,$key) {
                    return Html::a('Action', $url);
                },
	        ],
        ],
    ],
]); 
?>

GridView Column: Content Options [class, style etc]

If we would like to set the HTML attributes for ‘Gridview’ table cells in yii2.0, Just use the ‘contentOptions’ parameter for that cell. We will call one function this parameter. The function parameter should be like this ‘function ($model, $key, $index, $column){}’ and it will return the array with different type of attribute for cells like class, style, data-key, etc


<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        //.........
        // format one
        [
            'attribute'=>'parentid',
            'label'=>'Parent Name',
            'contentOptions' =>function ($model, $key, $index, $column){
                return ['class' => 'tbl_column_name'];
            },
            'content'=>function($data){
                return "value";
            }
        ],
        // format two
        [
            'attribute'=>'child_id',
            'contentOptions' =>['class' => 'table_class','style'=>'display:block;'],
            'content'=>function($data){
                return "value";
            }
        ],
        //.........
        ['class' => 'yii\grid\ActionColumn'],
    ],
 ]); 
 ?>

GridView Column: Add Image

Add Image in gridview column of yiiframwork 2.0.
Yii2 Gridview Column Image Link


<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        //.........
        [
            'label'=>'Image',
            'format'=>'raw',
            'value' => function($data){
                $url = "http://127.0.0.1/yii2/logo.png";
                return Html::img($url,['alt'=>'yii']); 
            }
        ],
        //.........
        ['class' => 'yii\grid\ActionColumn'],
	],
]); 
?>

Add a link in gridview column of yiiframwork 2.0.


<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        //.........
        [
            'label'=>'Custom Link',
            'format'=>'raw',
            'value' => function($data){
                $url = "https://www.bsourcecode.com";
                return Html::a('Go Link', $url, ['title' => 'Go']); 
            }
        ],
        //.........
        ['class' => 'yii\grid\ActionColumn'],
    ],
]); 
?>

GridView Column: Data From Relational Table Or Model

If you want to display a value from relational data, using the below code. We displayed value from model function and inline method.


<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        //.........
        [
            'attribute'=>'parentid',
            'label'=>'Parent Name',
            'format'=>'text',//raw, html
            'content'=>function($data){
                return $data->getParentName();
            }
        ],
        // ***** OR *****
        'parent.categoryname',
        //.........
        ['class' => 'yii\grid\ActionColumn'],
	],
]); 
?>
Category Model

<?php
namespace app\models;
use Yii;
//........
class TblCategory extends \yii\db\ActiveRecord
{
	.........
    public function getParent()
    {
        return $this->hasOne(TblCategory::className(), ['categoryid' => 'parentid']);
    }

    public function getParentName(){
        $model=$this->parent;
        return $model?$model->categoryname:'';
    }
    ..........
}
?>

Gridview Column: Date format

To display the date format in gridview Use the below code. We can set the format like ‘date’,’datetime’,’time’ etc.


<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        //.........
        [
            'attribute'=>'createdon',
            'label'=>'Created On',
            'format'=>'datetime',//date,datetime, time
            'headerOptions' => ['width' => '200'],
        ],
        [
            'attribute' => 'createdon',
            //'format' => ['raw', 'Y-m-d H:i:s'],
            'format' =>  ['date', 'php:Y-m-d H:i:s'],
            'options' => ['width' => '200']
        ],
        .........
        ['class' => 'yii\grid\ActionColumn'],
    ],
]); 
?>

Gridview Filter : Select Box

By default, gridview filter is having ‘textbox’. We can change it as ‘dropdownbox’ using below code.

Format 1

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        //.........
        [
            'attribute'=>'isactive',
            'filter'=>array("1"=>"Active","2"=>"Inactive"),
            //TblCategory::get_status(), 
        ],
        //.........
        ['class' => 'yii\grid\ActionColumn'],
    ],
]); 
?>
Format 2

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        //.........
        [
            'attribute'=>'isactive',
            'filter'=>TblCategoryStatus::get_status(), 
        ],
        //.........
        ['class' => 'yii\grid\ActionColumn'],
    ],
]); 
?>
Get Status List From Model

//..........
public static  function  get_status(){
    $cat = TblCategoryStatus::find()->all();
    $cat = ArrayHelper::map($cat, 'id', 'name');
    return $cat;
}
//.......

 

Leave a Reply

Your email address will not be published. Required fields are marked *