A summary of the usage of the GridView in Yii2

Source: Internet
Author: User
This article mainly introduces about the YII2 in the use of the GridView summary, has a certain reference value, now share to everyone, the need for friends can refer to

We are using the yii2.0.14 version, in order to learn convenience, in question-and-answer writing.

Start GridView

The GridView is mainly to achieve the table reuse, especially when we do backstage, you find forms and tables occupy most of the page, and the table style is a high degree of unity, then if there is such a pendant, the incoming dataset automatically render the table that much better.

So the GridView appeared, a detailed, stable enough form to render the pendant.

In general, the GridView is used in conjunction with various Dataprovider, for the Dataprovider in the YII2 framework I have written an article before, and you can look at it, which will help you learn about the GridView. Talking about the 3 data providers in Yii2 and their use with the GridView

Before learning the GridView pendant, we need to understand the structure of the GridView, see.

In a nutshell, a GridView consists of n columns, and each column has its own header, content, and footer operations, which are reflected in the GridView code.

try {    echo gridview::widget ([        ' dataprovider ' = ' $dataProvider,                ' columns ' =>[            ' id ',            ' Created_at:datetime: Generate time ',            [                ' label ' + ' member name ',                ' attribute ' = ' username ',                ' format ' = ' Text '            ],        ]    );} catch (\exception $e) {    //Todo}

Of course Yii2 has done quite a little detail, you can not write Columns,gridview will automatically render each column according to Dataprovider, then we start the question and answer area, through a question to understand the GridView in depth.

Preparation phase

For the smooth answer, we modeled a data table as a source of the result set.

City
ID username Province Created_at Updated_at Sex
1 Abei Heilongjiang Heihe river 1514201852 1528707743 1
2 Comprehensive Jilin Changchun 1528115243 1528115243 1
3 Be Xin Jilin Songyuan 1528180018 1528255890 1
4 Zhangnan Liaoning Shenyang 1528265883 1528265883 0







Column

In the a series, let's first talk about how to use the column in the GridView.

A1. Please render the ID, username, province, city, and sex.

When we only need to $dataprovider certain properties of each object, we must specify the Columns property, the code is as follows

try {    echo gridview::widget ([        ' dataprovider ' = ' $dataProvider,                ' columns ' =>[            ' id ',            ' Username ',            ' province ',            ' city ',            ' Created_at '        ]    );} catch (\exception $e) {    //Todo}

The results are as follows

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

In A1 we found that the head of each column is in English and now wants to change to Chinese, there are three ways

Method 1 Change the Attributelabels method in the corresponding model

App\models\userclass User extends \yii\db\activerecord {public        function attributelabels () {        return [            ' id ' = ' + ' id ',            ' username ' = ' user name ',            ' province ' = ' province ',            ' city ' + ' cities ', ' created_at ' and '            = ' New Time ',            ' updated_at ' = ' recent update ',            ' sex ' = ' gender ', '        ;    }       }

When we reset the Attributelabels method, the corresponding GridView will automatically fetch it.

Method 2 Sets the Label property of a column, as shown in the following code

try {    echo gridview::widget ([        ' dataprovider ' = = $dataProvider,                ' columns ' =>[            ' username: Text: User name '        ]    ]);} catch (\exception $e) {    //Todo}

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

Method 3 uses the custom property of the GridView, as shown in the following code

try {    echo gridview::widget ([        ' dataprovider ' = = $dataProvider,                ' columns ' =>[            [                ' label ' = > ' username ',                ' attribute ' = ' username ']            ]    );} catch (\exception $e) {    //Todo}

The above 3 methods can be, from 1-3 more flexible, of course, the code is more and more large, the 1th is the simplest, the 3rd most flexible.

A3. I don't want time stamps.

In A2, we see that the new time column of the contents of the direct appearance of the time stamp, how to become the corresponding time that? There are actually two ways to do this.

Method 1 Sets the Format property of column

try {    echo gridview::widget ([        ' dataprovider ' = = $dataProvider,                ' columns ' =>[            ' created_at: DateTime '        ]    ]);} catch (\exception $e) {    //Todo}

Method 2 is implemented by passing the column of an array type and setting its value, as in the following code

try {    echo gridview::widget ([        ' dataprovider ' = = $dataProvider,                ' columns ' =>[            [                ' Attribute ' = ' created_at ',                ' value ' =>function ($model) {//parameter for this row Record object                    return date ("Y-m-d h:i:s", $model- >CREATED_AT),                }            ]        ]    ); catch (\exception $e) {    //Todo}

from A3 Method 1 and Method 2, in fact, Method 1 is more a shortcut to Method 2, so we can achieve this problem by setting the Format property of the array type column equal to DateTime.

A4. I want to define a property called provinces and municipalities, merging provincial and municipal field contents

By learning about A2 and A3, I think you already know that you can solve this by using the array type column, yes, the following code

try {    echo gridview::widget ([        ' dataprovider ' = = $dataProvider,                ' columns ' =>[            [                ' label ' = > ' provinces ',                ' value ' =>function ($model) {                    return ' {$model->province}-{$model->city} ';                }    ] ]);} catch (\exception $e) {    //Todo}

The value property represents the data content of this cell, returning the result as if it were a result diagram.

But the problem arises, I hope the provinces and cities in a column according to the provincial attributes to sort, how to do? You only need to specify attribute, which is one way we can control the sorting of columns.

try {    echo gridview::widget ([        ' dataprovider ' = = $dataProvider,                ' columns ' =>[            [                ' label ' = > ' provinces ',                ' attribute ' = ' province ',                ' value ' =>function ($model) {                    return ' {$model->province}-{ $model->city} ";                }            ]        ]    ]);} catch (\exception $e) {    //Todo}

A5. How do I control column sorting?

From A4 we know that by setting the attribute property of column to control sorting, but attribute's intention is not here, so our standard way to get rid of sort or set sorting is through its enablesorting property.

try {    echo gridview::widget ([        ' dataprovider ' = = $dataProvider,                ' columns ' =>[            [                ' label ' = > ' provinces ',                ' attribute ' = ' province ',                ' enablesorting ' =>false,                ' value ' =>function ($model) {                    return "{$model->province}-{$model->city}";                }]]    );} catch (\exception $e) {    //Todo}

The default enablesorting is true, which can be set to False to cancel the column sorting function, such as.

A6. How is the style of the column controlled?

Now that you know the 5 techniques for using the GridView, we continue, in A6 we try to change the style of a column in a table. For column styles, the GridView provides 3 properties, Headeroptions, Contentoptions, and Footeroptions, respectively.

Now let's do a demand, the provinces and cities of this column personalization, column header programming red, column content programming blue, as follows

try {    echo gridview::widget ([        ' dataprovider ' = = $dataProvider,                ' columns ' =>[            [                ' label ' = > ' provinces ',                ' attribute ' = ' province ',                ' enablesorting ' and false,                ' value ' =>function ($model) {                    return "{$model->province}-{$model->city}";                },                ' headeroptions ' + [' style ' = ' color:red ' ],                ' contentoptions ' = [' style ' = ' color:blue '],]]    );} catch (\exception $e) {    //Todo}

Yes, you can use this column of Headeroptions and Contentoptions

One of the areas 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 to the TH and TD labels, adding properties like style to it, so if you have other HTML tags in your th or TD tag, you won't be able to define the style directly. This problem can be solved by CSS classes at this time.

A7. About the use of footeroptions in the GridView.

In A6 we say that the GridView column has a footeroptions attribute, so what does this attribute do? Parsing from a word is a property that controls column footer (such as style, etc.), but where is footer??? Where is it?

You need to set the GridView Showfooter equal to True before you can. Before we can.

try {    echo gridview::widget ([        ' dataprovider ' = = $dataProvider,                ' columns ' =>[            [                ' label ' = > ' provinces ',                ' attribute ' = ' province ',                ' enablesorting ' and 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}

In the Showfooter=true sky, the column of the footeroptions can fly freely.

In principle, the result of ' Showfooter ' =>true is to have the following code appear in table

<tfoot>   <tr>       <td></td>       <td></td>       <td></td>   <tr> </tfoot>

So the footeroptions of each column controls the TD that corresponds to this column in the TFOOT.

A8.footerrowoptions you use it for dry hair?

In our swagger with the A8 in the Showfooter, suddenly phpstorm automatically associated with a footerrowoptions, what is this thing?

Footerrowoptions is the property of the GridView, which controls the properties of the TFOOT tr tag, and simply says that the effect you see in each cell on Tfoot is Footerrowoptions + footeroptions (in terms of style).

For example, for the above examples we are under configuration footerrowoptions

' Footerrowoptions ' =>[' style ' = ' font-size:20px; '

Then you will find that the yellow font becomes 20px.

Note: These xxxoptions in A6, A7, and A8 can control the properties of the tag, not just the style.

A9.showfooter's Big family

From the A7 we know the showfooter of the GridView, which determines whether the table shows tfoot information, in addition to some other members of the show family.

    • Showheader can control whether the table's head is displayed by default.

    • Showonempty when the data is empty, the table frame exists and does not exist by default.

A10. The magician's Visible trick

In this episode, we say the GridView column's Visible property, which defaults to TRUE for this column display, can hide a column by setting the Visible property, which hides the non-CSS display:none, but removes the column when the table is rendered.

You might ask, if I'm going to use visible to hide a column, wouldn't it be nice if I didn't write this column?

Yes, your ideas are correct, but visible is the ability to pass an expression to make logical judgments, such as the following requirements when the 1th administrator log in, you can see a column of provinces and cities.

try {    echo gridview::widget ([        ' dataprovider ' = = $dataProvider,                ' columns ' =>[            [                ' label ' = > ' provinces ',                ' attribute ' = ' province ',                ' enablesorting ' and false,                ' value ' =>function ($model) {                    return "{$model->province}-{$model->city}";                },                ' visible ' = = (Yii:: $app->admin->id = = = = 1]        ],        ' Showfooter ' =>true    ]);} catch (\exception $e) {    //Todo}
A1-A10 We focus on the public properties of each column of the GridView, which is not all, for different types of columns there are other properties, such as DataColumn, Actioncolumn, Checkboxcolumn, etc. For different types of the explanation of the column, to be released later.

Gridview

Next we go into the B series, the B series focuses on the GridView.

B1 About layout layouts

By default, the GridView layout is as

This layout is derived from the GridView Layout property, and we can change the template, for example, to remove summary.

try {    echo gridview::widget ([        ' dataprovider ' = = $dataProvider,                ' columns ' =>[                    ],        ' layout ' = > "{items}\n{pager}"    ]);} catch (\exception $e) {    //Todo}

There are 5 values that can be used in layout, {summary}, {errors}, {items}, {sorter}, and {pager}.

B2. Specify the default type for the column Datacolumnclass

In a table each column has a different role, there are some types of data, some check box type, there are 5 kinds of

    1. Actioncolumn

    2. Checkboxcolumn

    3. DataColumn

    4. Radiobuttoncolumn

    5. Serialcolumn

You can set the default type for a column by using the GridView, and of course you can specify its class individually for special classes.

try {    echo gridview::widget ([        ' dataprovider ' = = $dataProvider,                ' columns ' =>[                    ],        ' Datacolumnclass ' = "Yii\grid\datacolumn"    ]);} catch (\exception $e) {    //Todo}

B3.caption Property

We can implement the caption function of the table by setting the Caption property of the GridView, which is useful for table purposes.

try {    echo gridview::widget ([        ' dataprovider ' = = $dataProvider,        ' columns ' =>[                    ],        ' Caption ' + ' membership list "    ]);} catch (\exception $e) {    //Todo}

As follows

Needless to say, the GridView also provides the Captionoptions property to let you control the properties of the caption.

B4.tableoptions and Options Properties

Some developers of these two properties may be confused, and then I'll use a graph to give you an instant understanding.

That is, the GridView rendering of the first to get a P container, which is the representative of the GridView, and then put various elements in this container, such as {summary}, {items} and so on.

    • The options control the properties of the P container, adding a class= "Grid-view" by default

    • Tableoptions controls the properties of the {items} table, adding a class= "table table-striped table-bordered" by default

Are you going to change the style class for table now?

B5. A bunch of good friends headerrowoptions and Footerrowoptions

We spoke of footerrowoptions usage in A8, and Headerrowoptions's usage is the same as it, except that it manages the properties of the THEAD under TR.

B6.rowoptions

Learned the B5, you may look at the rowoptions one eye to see through, yes it is to manage each TR under the tbody, but it is more powerful, in addition to directly receive an array can also pass the anonymous function.

You can integrate your logic, for example, now we want to use rowoptions to achieve the function of interlaced color, come on.

try {    echo gridview::widget ([        ' dataprovider ' = = $dataProvider,        ' columns ' =>[                    ],        ' Rowoptions ' =>function ($model, $key, $index) {            if ($index%2 = = = 0) {                return [' style ' = ' background:red '];            }        }    ]);} catch (\exception $e) {    //Todo}

Aim to achieve, look at the effect

For 4 parameters of the number of anonymous rows received by Rowoptions, here is a description

    • $model: The object that is currently being rendered

    • $key: The current object's gradual

    • $index: For the current page, starting with 0, line by row plus 1

    • $grid: GridView Object

B7. BeforeRow and Afterrow

This is a pair of very flexible properties that receive an anonymous function. Indicate what happens before and after a row is rendered, respectively? Of course, it's up to you to decide what happens.

Keep in mind that the results returned by the anonymous function are also included as a row into the rendering process, for example, when we encounter an odd number of lines to add a line below this line, you can

try {    echo gridview::widget [        ' dataprovider ' + $dataProvider,        ' tableoptions ' = [' class ' = ' = ' Table Table-bordered '],        ' columns ' =>[            ' id ',            ' username:text: User name ',            ...        ],        ' afterrow ' = >function ($model, $key, $index, $grid) {            if ($index + 1)%2! = 0) {                return ' <tr><td colspan= ' 4 ' > I am base </td></tr> ";            }        }    ]);} catch (\exception $e) {    //Todo}

Very well, got the results we wanted.

B8. Two small pots of friends Placefooterafterbody & Emptycell

Two small attributes of very detail

    • Placefooterafterbody when we want to show footer, the Placefooterafterbody property determines where the HTML will be placed on the table, by default, after the header, You can choose Placefooterafterbody=true to put footer behind the body. This feature is only supported in yii2.0.14.

    • Emptycell is also a small detail, if a cell is empty, what character is populated with that? By default, you can re-specify it.

Summary

Unconsciously wrote more than 3,000 words, this would like a complete gridview explanation, now seems more difficult, after all, there are many types of columns to study to share, or become a topic bar, next I will do a separate analysis of each column, I hope that you useful.

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.