I’ve often been asked about the GridView configuration of Yii2, and I’ve recently been asked in the group, so I thought it was time to post a tutorial.

We use yii2.0.14, in order to facilitate learning, written in question and answer style.

Start the GridView

The GridView is mainly for table reuse, especially when we do the background, you find that forms and tables occupy most of the page, and the table style is highly uniform, so it would be nice to have a widget that automatically renders the table in the data set.

Here comes the GridView, a detailed, stable table rendering widget.

Generally, GridView is used with various dataProviders. I wrote an article about dataProviders in the YiI2 framework that will help you learn about GridView. Three data providers in YII2 and their use with GridView

Before we learn about the GridView widget, we need to understand the structure of the GridView.

In simple terms, a GridView consists of N columns, each of which has its own header, content, and footer operations, as reflected in the GridView code

try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        
        'columns'= > ['id'.'created_at:datetime: generation time '['label'= >'Member Name'.'attribute'= >'username'.'format'= >'text']]]); }catch(\Exception $e){
    // todo
}
Copy the code

Of course, yii2 has done a lot of detail, you can not write columns, the GridView will automatically render each column according to the dataProvider, next we will start the question and answer area, through the question and answer to understand the GridView in depth.

Preparation stage

To facilitate the q&A, we simulated a data table as the source of the result set.

id username province city created_at updated_at Sex
1 abei heilongjiang Heihe river 1514201852 1528707743 1
2 considerate Ji Lin changchun 1528115243 1528115243 1
3 BaiXin Ji Lin matsubara 1528180018 1528255890 1
4 nan liaoning shenyang 1528265883 1528265883 0

Column

In series A, let’s talk about using A column in A GridView.

A1. Please render id, username, province, city and sex.

When we only need some properties of each object $dataProvider, we must specify the columns property as follows

try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        
        'columns'= > ['id'.'username'.'province'.'city'.'created_at']]); }catch(\Exception $e){
    // todo
}
Copy the code

The results are as follows

A2. I want to change the header content of the column

In A1, we find that the head of each column is In English. Now, there are three ways to change it to Chinese

Method 1 changes the attributeLabels method in the corresponding model

// app\models\User

class User extends \yii\db\ActiveRecord {
	
    public function attributeLabels(a){
        return [
            'id'= >'ID'.'username'= >'Username'.'province'= >'province'.'city'= >'city'.'created_at'= >'New time'.'updated_at'= >'Recently Updated'.'sex'= >'gender',]; }}Copy the code

When we reset the attributeLabels method, the corresponding GridView will automatically pick it up.

Method 2 sets the label property for a column, as follows

try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        
        'columns'= > ['username:text: username ']]); }catch(\Exception $e){
    // todo
}
Copy the code

You can do this by setting the label attribute of the column, like username:text: the username, separated by a colon:, the attribute name, format, and label.

Method 3 uses the GridView’s custom properties, as shown below

try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        
        'columns'= > [['label'= >'Username'.'attribute'= >'username']]]); }catch(\Exception $e){
    // todo
}
Copy the code

The above three methods can be used, from 1 to 3, more and more flexible, of course, more and more code, the first is the simplest, the third is the most flexible.

A3. I don’t want a time stamp

In A2, we can see that the new time column contains the timestamp. There are actually two ways to approach this problem.

Method 1 sets the format attribute for column

try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        
        'columns'= > ['created_at:datetime']]); }catch(\Exception $e){
    // todo
}
Copy the code

Method 2 does this by passing an array type column and setting its value, as follows

try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        
        'columns'= > [['attribute'= >'created_at'.'value'= >function($model){// The parameter is the row record object
                    return date("Y-m-d H:i:s",$model->created_at); }]]]); }catch(\Exception $e){
    // todo
}
Copy the code

Method 1 is more of a shortcut to method 2, so we can do this by setting the format property for column to be equal to datetime.

A4. I want to define an attribute called province and merge the contents of province and city fields

From A2 and A3, I think you already know that you can solve this problem with column of array type. Yes, here’s the code

try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        
        'columns'= > [['label'= >'and'.'value'= >function($model){
                    return "{$model->province}-{$model->city}"; }]]]); }catch(\Exception $e){
    // todo
}
Copy the code

The value property represents the data content of this cell and returns the result, just like the result graph.

I want the list of provinces and cities to be sorted by province attribute. What should I do? You just specify the attribute, which is one way we control column sorting.

try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        
        'columns'= > [['label'= >'and'.'attribute'= >'province'.'value'= >function($model){
                    return "{$model->province}-{$model->city}"; }]]]); }catch(\Exception $e){
    // todo
}
Copy the code

A5. How do I control column ordering?

We know from A4 that sorting is controlled by setting the attribute attribute of column, but the original intention of attribute is not this, so our standard method of removing sorting or setting sorting is realized by its enableSorting attribute.

try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        
        'columns'= > [['label'= >'and'.'attribute'= >'province'.'enableSorting'= >false.'value'= >function($model){
                    return "{$model->province}-{$model->city}"; }]]]); }catch(\Exception $e){
    // todo
}
Copy the code

The default enableSorting is true, and you can disable this column sorting by setting it to false, as shown below.

A6. How is the style of the column controlled?

Now that you know the five GridView techniques, let’s move on. In A6 we tried to change the style of a column in the table. For the column style, the GridView provides three properties, headerOptions, contentOptions, and footerOptions.

Now let’s make a requirement, personalize the province column, program the header of the column in red, and program the content of the column in blue, as follows


try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        
        'columns'= > [['label'= >'and'.'attribute'= >'province'.'enableSorting'= >false.'value'= >function($model){
                    return "{$model->province}-{$model->city}";
                },
                'headerOptions'= > ['style'= >'color:red'].'contentOptions'= > ['style'= >'color:blue']]]]); }catch(\Exception $e){
    // todo
}
Copy the code

Yes, use headerOptions and contentOptions in this column

One important thing to note is that we use the browser’s F12 to look at the color-coded columns.

As you can see, headerOptions and contentOptions directly apply to th and TD tags, adding attributes like style to them, so if you have other HTML tags in th or TD tags, defining style directly won’t work. You can solve this problem with CSS classes.

A7. Using footerOptions in a GridView.

In A6 we said that the GridView column has a footerOptions property. What does this property do? Word parsing controls the attributes of the footer column (style, etc.), but where is the footer? Where? Where?

The GridView showFooter must be set to true. Just can just can.

try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        
        'columns'= > [['label'= >'and'.'attribute'= >'province'.'enableSorting'= >false.'value'= >function($model){
                    return "{$model->province}-{$model->city}";
                },
                'headerOptions'= > ['style'= >'color:red'].'contentOptions'= > ['style'= >'color:blue'].'footerOptions'= > ['style'= >'color:yellow']]].'showFooter'= >true
    ]);
}catch(\Exception $e){
    // todo
}
Copy the code

Under the showFooter=true sky, the footerOptions column can fly freely.

In principle, ‘showFooter’=>true results in the following code for the table

<tfoot>
   <tr>
   	<td></td>
   	<td></td>
   	<td></td>
   <tr> 
</tfoot>
Copy the code

So footerOptions for each column controls the TD for that column in TFoot.

A8. What do you do with footerRowOptions?

When we are using showFooter in A8, PhpStorm automatically generates a footerRowOptions. What is that?

FooterRowOptions is a GridView property that controls the TR attribute of Tfoot. Simply put, what you end up seeing on each cell on Tfoot is a combination of footerRowOptions + footerOptions (in style terms).

For example, in the example above we can configure footerRowOptions

'footerRowOptions'= > ['style'= >'font-size:20px; ']
Copy the code

You’ll notice that the yellow font has changed to 20px.

Note that xxxOptions in A6, A7, and A8 control the attributes of the tag, not just the style.

A9. ShowFooter’s extended family

From A7 we know about the GridView showFooter, which determines whether the table displays tfoot information, as well as other members of the Show family.

  • ShowHeader controls whether the header of the table is displayed, which is displayed by default.
  • ShowOnEmpty Specifies whether the table frame exists when the data is empty.

A10. Magic visible trick

The visible property of the GridView column is set to true to indicate that the column is displayed. By setting the visible property to hide a column, you can hide non-CSS display: None. Instead, the column is removed when rendering the table.

You might ask, if I wanted to use Visible to hide a column, wouldn’t I just not write that column?

Yes, you are right, but visible can pass an expression to implement a logical judgment, such as the following requirement: when administrator 1 logs in, the list of provinces and cities can be seen.

try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        
        'columns'= > [['label'= >'and'.'attribute'= >'province'.'enableSorting'= >false.'value'= >function($model){
                    return "{$model->province}-{$model->city}";
                },
                'visible'=>(Yii::$app->admin->id === 1)]],'showFooter'= >true
    ]);
}catch(\Exception $e){
    // todo
}
Copy the code

We will focus on the common attributes of each column in the GridView. This is not all. There are other attributes for different types of columns, such as DataColumn, ActionColumn, CheckboxColumn, etc.


GridView

So let’s move on to series B, and series B focuses on GridView.

B1 About layout layout

The default GridView layout is shown below

The layout comes from the GridView layout property, and we can change the template to remove the summary, for example.

try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        
        'columns'= > [].'layout'= >"{items}\n{pager}"
    ]);
}catch(\Exception $e){
    // todo
}
Copy the code

Layout has five values you can use: {summary}, {errors}, {items}, {sorter}, and {pager}.

B2. Specify the default type of the column, dataColumnClass

Each column in a table has a different role, some data type, some check box type, there are five

  1. ActionColumn
  2. CheckboxColumn
  3. DataColumn
  4. RadioButtonColumn
  5. SerialColumn

The GridView allows you to set the default type of a column, although you can specify its class individually for a particular class.

try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        
        'columns'= > [].'dataColumnClass'= >"yii\grid\DataColumn"
    ]);
}catch(\Exception $e){
    // todo
}
Copy the code

B3. The caption property

We can set the GridView caption property to achieve the caption function of the table, as a table.

try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        'columns'= > [].'caption'= >"Membership List"
    ]);
}catch(\Exception $e){
    // todo
}
Copy the code

The renderings are as follows

Needless to say, the GridView also provides a captionOptions property that lets you control the Caption properties.

B4. TableOptions and Options properties

These two properties can be confusing for some developers, but I’ll give you a quick picture to make it clear.

The GridView renders a div container, which is a representation of the GridView, and then places elements in the container, such as {summary}, {items}, etc.

  • Options controls div container properties. Default class=”grid-view”
  • TableOptions controls the attributes of the {items} table. By default, add a class=”table table-striped table-bordered”

Can you change the table style class now?

B5. A bunch of good gay friends headerRowOptions and footerRowOptions

FooterRowOptions is used in A8. HeaderRowOptions is used in the same way, except that it manages the attributes of tr under thead.

B6.rowOptions

If you learn B5, you can see right away that rowOptions is designed to manage every TR under TBody, but it is more powerful and can pass in anonymous functions in addition to receiving an array directly.

You can use your own logic, for example, now we are going to use rowOptions to implement interrow color, go ahead.

try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        'columns'= > [].'rowOptions'= >function($model,$key, $index){
            if($index%2= = =0) {return ['style'= >'background:red']; }}]); }catch(\Exception $e){
    // todo
}
Copy the code

Aim achieved, look at the effect

The four parameters for the number of anonymous rows received by rowOptions are explained here

  • $model: The object currently being rendered
  • $key: Progressive of the current object
  • $index: for the current page, start at 0 and increment by 1 line by line
  • $grid: the GridView object

B7. BeforeRow and afterRow

This is a very flexible pair of attributes that accept an anonymous function. What happens before and after a row is rendered? What happens is up to you, of course.

Keep in mind that the result returned by the anonymous function will also be included as a line in the rendering process. For example, when we encounter an odd number, we can add a line below this line

try {
    echo GridView::widget([
        'dataProvider' => $dataProvider,
        'tableOptions'= > ['class'= >'table table-bordered'].'columns'= > ['id'.'username:text: username '. ] .'afterRow'= >function($model,$key, $index,$grid){
            if(($index+1) %2! =0) {return "< TD colspan='4'> I am cardinality 
      "; }}]); }catch(\Exception $e){
    // todo
}
Copy the code

Very good. We got what we wanted

B8. PlaceFooterAfterBody & emptyCell

Two very detailed little properties

  • PlaceFooterAfterBody When we want to display footer, the placeFooterAfterBody attribute determines where to place the HTML in the table. By default, it goes after the header. You can place the footer after the body by selecting placeFooterAfterBody=true. This feature was only supported in yii2.0.14.
  • EmptyCell is another small detail. If a cell is empty, what character is used to fill it? The default is  , which you can respecify.

summary

After writing more than 3000 words, I wanted to complete the GridView explanation in one article, but now it seems to be difficult. After all, there are many types of columns to study and share, so LET’s change it into a special topic. Next, I will make a separate analysis for each column, hoping it will be useful to you.

Thanks for reading more Yii in-depth articles