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 = "http://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;
}
//.......

  • Mark Johnson

    I just wanted to say: THANK YOU!!! this is the kind of example that should be on the Yii Api documentation, you have saved me a ton of heart ache! 🙂

    • m bala

      Thank you Mark. If you want any new topics Just share with me in comments

      • Mark Johnson

        Well actually, I have been looking for information on printing data.
        Maybe something that will download as a PDF or CSV.
        Do you happen to know of anything?

        • m bala

          I tried this concept in Yii1.x. Surely I will try this concept in yii2.x in this week….

  • Nhexia

    Thanks Bro!

  • Ben

    Hi,

    I have a posts CRUD with an empty field called “author_id”, upon create my post I would like to have the author id passed into that empty field automatically without having the user viewing that field, How to pass the data from the controller onto a view please, It would have eben great to have tutorials about this please. Just a simple example showing how to pass user id or any other ids upon the create action.

    Thanks!

    • m bala

      Hi Ben,
      From my understanding, Just make a one hidden field for authod_id. When you submit the post, It will be posted with empty value.

  • Ben

    Thank you for the reply. But what I would like to do is hide it and still have the value passed in the database to then output it somewhere else later on. I just need to visually not show it to the user but still have the data passing behind by having the user id adding itself in that post. thank you!

    • m bala

      Please post your code as screen shot and ask Where is your problem?

      Note : If you dont want to send the values to database just use unset() for that value or make it null

      • Ben

        Thank you Mbala

  • Bimal

    How do I hide the new created button ? with ‘visible’=>$model->flag =0;

    • m bala

      Try this method.
      We can do all the logical work inside the function and have to access data like $data[‘id’] etc
      ‘template’ => ‘{myedit} {settings} {delete}’,
      ‘buttons’ => [
      ‘myedit’=>function ($url,$data,$index) {
      return false;
      },

      ……….

  • Raj

    How to create a new button inside the grid view and how to give the link

  • Nerison Sayson Pitogo

    how to make the headers fixed?? even scrolling down.

    • m bala

      You have to write css class and add it to gridview. I think it is based on your css style.

  • Ahmad Muhammad Ahmad

    Is it possible to populate all the columns of grid view from a single array, i.e. I have an array in a model class and the array stores data in key value pairs (Each key corresponds to a column in grid view) and I want to display data in grid view from the array. How I can do this?

    • Christian Joseph Dalisay

      You can use non-activeform. Check the gridview demo of kartik/grid/GridView.

  • Christian Joseph Dalisay

    Is there any way to hide a DataColumn using a flag. Usually, it is done by ‘visible’ => false. Here, the DataColumn should be visible if the role of the user is ‘administration’. It seems not working.

    ‘visible’ => function ($url,$data,$index) {
    (Yii::$app->session->get(‘role’) === ‘administration’) ? true : false;
    }

  • Abdul

    i have two tables one is tbl_customer another one is tbl_city tbl_customer has customerid,name,gender,cityid and mobile number where tbl_city has cityId and cityname.I have one cdetailview and i want to set city name on cdetailview and i am getting data from city model so here i m getting cityId with the help of this id how i can get city name from city table any suggestion please help me

  • Giovanni R (Balo)

    WOW! Wounderfull resources! Just one question… in my GridView i have setted a field as
    [
    ‘attribute’=>’createdBy.username’,
    ‘label’=>’Autore’,
    ‘format’=>’text’,
    ],
    instead of ‘created_by’, but now i have no more the filter for my column. How can i add it again?

  • john sunam

    how do i give the url to the newly add button??

  • remrem

    hello. i have a problem here.
    i have three tables and in each table. i want to add an specific and unique action for each of the three table.
    i
    have tried adding to the ActionColumn.php but it affects all the three
    table and not just the table where i want to add that. i hope that you
    could help me with this.
    thanks a lot

    • Give me more details. Which type of action you are going to apply and Are you using 3 tables in single gridview?

  • Hashim Zein

    Hi. How do I create a tooltip on the column header of the gridview? Thanks.

  • nan_do9

    That such friends as I can make me paint the cell depends on an example value if it is the red value that the red cell pinches me.

    GridView::widget([
    ‘dataProvider’ => $dataProvider,
    ‘filterModel’ => $searchModel,
    ‘columns’ => [
    [‘class’ => ‘yiigridSerialColumn’],

    ‘id’,
    ‘shir’,
    ‘color’,
    [‘class’ => ‘yiigridActionColumn’],
    ],
    ]);