Common yii2 GridView operations, yii2gridview

Source: Internet
Author: User

Common yii2 GridView operations, yii2gridview

Author: White Wolf Source: http://www.manks.top/article/yii2_gridview

The copyright of this article belongs to the author. You are welcome to repost this article, but you must keep this statement without the author's consent and provide the original article connection clearly on the article page. Otherwise, you will be entitled to pursue legal liability.

I have collected a summary of most of the problems that occur in the GridView on the network. I hope this will help you.

If there is a common problem with the GridView that is not mentioned below, leave a message below and I will add it.

  • Drop-down search

  • Format and search for dates

  • Display Based on Parameters

  • Click to jump

  • Show Image

  • Html Rendering

  • Custom button

  • Set the width and other styles

  • Custom Field

  • Customize the row style

  • Add button to call js operation

Drop-down search. Let's take a look at the expected

How can we implement this feature? Considering that a data table may have many drop-down fields, we first implement a method in its model to facilitate subsequent operations.

1/** 2 * drop-down Screen 3 * @ column string field 4 * @ value mix field value, if this parameter is not specified, the returned field array 5 * @ return mix returns a value or array 6 */7 public static function dropDown ($ column, $ value = null) 8 {9 $ dropDownList = [10'is _ delete' => [11 '0' => 'display', 12' 1' => 'delete', 13], 14 'is _ hot '=> [15 '0' => 'no', 16 '1' =>' Yes ', 17], 18 // There are new fields to implement the drop-down rule, you can add 19 as above //...... 20]; 21 // display the corresponding value 22 if ($ value! = Null) 23 return array_key_exists ($ column, $ dropDownList )? $ DropDownList [$ column] [$ value]: false; 24 // returns the associated array. The user drop-down filter implements 25 else26 return array_key_exists ($ column, $ dropDownList )? $ DropDownList [$ column]: false; 27}

 

Then let's go to the Code to see how to implement the drop-down search

<?= GridView::widget([    'dataProvider' => $dataProvider,    'columns' => [        // ......        [            'attribute' => 'is_hot',            'value' => function ($model) {                return Article::dropDown('is_hot', $model->is_hot);            },            'filter' => Article::dropDown('is_hot'),        ],        [            'attribute' => 'is_delete',            'value' => function ($model) {                return Article::dropDown('is_delete', $model->is_delete);            },            'filter' => Article::dropDown('is_delete'),        ],        // ......    ],]); ?>

 

In this way, we simply implement two drop-down effects. To implement the filter function, you can add the search criteria for this field in your dataProvider.

 

Date formatting. Let's take a look.

We will discuss the situation in detail.

1. If the time format of your database Field created_at is date or datetime, it is very easy to directly output this field created_at in the gridview, as shown on the right

2. If the timestamp type stored in the database is shown on the left side of the data center, output the data as follows:

[    'attribute' => 'created_at',    'value' => function ($model) {        return date('Y-m-d H:i:s', $model->created_at);    },],[    'attribute' => 'created_at',    'format' => ['date', 'Y-m-d H:i:s'],],

 

The preceding two formats can be output. However, if you want to implement the search mechanism, if your database is saved in the datetime type, it is very convenient, dataProvider does not need to be modified,

The Code is as follows:

$query->andFilterWhere([    // ......    'created_at' => $this->created_at,    // ......]);

 

If your database is saved with a timestamp,

Step 1: Modify the corresponding rule, as shown in

Step 2: Modify dataProvider by referring to the following code:

// In the search input box, the input format is generally, instead of the timestamp. // the output of 2016-01-01 is nothing more than the data of the day. Therefore, the Code is as follows if ($ this-> created_at) {$ createdAt = strtotime ($ this-> created_at); $ createdAtEnd = $ createdAt + 24*3600; $ query-> andWhere ("created_at >={$ createdAt} AND created_at <={ $ createdAtEnd }");}

 

Here is a small summary. We recommend that you use the datetime type. In my opinion, it is very troublesome to save the timestamp. If you have good suggestions, leave a message below for us to share.

 

Show Case of a column

Let's give a simple example.

Condition: There is a get parameter type.

Requirement: the column name is displayed only when the value of type is equal to 1. Otherwise, the column is not displayed.

The code is implemented as follows:

[    'attribute' => 'name',    'value' => $model->name,    'visible' => intval(Yii::$app->request->get('type')) == 1,],

 

The implementation method is also very simple.

 

Link clickable jump case

This is very similar to the html Rendering effect we will talk about next. Here we will talk about the format of the column attribute value. Which formats can be used to view the file yii \ i18n \ Formatter. php and various formats can be solved

[    'attribute' => 'order_id',    'value' => function ($model) {        return Html::a($model->order_id, "/order?id={$model->order_id}", ['target' => '_blank']);    },    'format' => 'raw',],

 

 

Show image Cases

Same as above. You only need to specify the format as image. The second parameter of format can be used to set the image size. For details, refer to the following code.

['Label' => 'Avatar ', 'format' => ['image', ['width' => '84 ', 'height' => '84 '], 'value' => function ($ model) {return $ model-> image;}],

 

 

Html Rendering case

For example, we have a field marked as title, but this title is different. ta contains html tags, we do not want to display the form <p> title123 <p> on the page. We want title123 to be displayed in the form of a p tag. For the code, refer to the following. You only need to specify the format as raw.

[    'attribute' => 'title',    'value' => function ($model) {     return Html::encode($model->title);     },    'format' => 'raw',],

 

 

Custom button Cases

We do not want to delete a button on the list page. We want to add a button such as getting xxx. How can this problem be solved? Here you need to set the ActionColumn class, modify the configuration item template, and add the get-xxx added to the template in the buttons item.

['Class' => 'yii \ grid \ actioncolumn', 'template' => '{get-xxx} {view} {update }', 'header' => 'operation', 'buttons' => ['get-XXX' => function ($ url, $ model, $ key) {return Html :: a ('get XXX', $ url, ['title' => 'get XXX']) ;},],],

 

 

Case study of setting width

For example, our title column is too long. Can you set the width of this column for me first?

Answer: Yes.

See the example:

[    'attribute' => 'title',    'value' => 'title',    'headerOptions' => ['width' => '100'],],

 

You only need to specify the configuration item headerOptions.

 

Case study of custom Fields

When is it customized? Here we add a column in the table and the database does not have a corresponding column. Assume that we add a column of order consumption amount money and this field does not exist in the table.

['Attribute' => 'consumption amount', 'value' => function ($ model) {// You can associate and obtain it based on other fields in the table.}],

 

 

Customize the row style

Some friends said that the row and row colors of the gridview table generated by gii are not obvious, and it seems uncomfortable. I am so embarrassed. We will not be held accountable for the specific problem. Let's see how to define the row style.

<?= GridView::widget([// ......    'dataProvider' => $dataProvider,    'rowOptions' => function($model, $key, $index, $grid) {        return ['class' => $index % 2 ==0 ? 'label-red' : 'label-green'];    },    // ......]); ?>

 

The previous operations are based on column columns. Here, we need to pay attention to configuring rowOptions because of row control. In addition, the custom label-red and label-green must have corresponding style implementations. Here we will look at the actual effect of the page.

 

Add button to call js operation case

The product manager is coming over there. Mr. Wang, you have a frequent function of modifying the status. You need to click the details page to modify the status each time, can I click the mouse on the list page to modify it successfully?

In fact, it is an asynchronous request operation in the forward state. Let's take a look at how it is implemented in the gridview.

['Class' => 'yii \ grid \ actioncolumn', 'header' => 'operation ', 'template' => '{view} {update-status}', 'buttons' => ['Update-status' => function ($ url, $ model, $ key) {return Html: a ('Update status', 'javascript:; ', ['onclick' => 'Update _ status (this ,'. $ model-> id. ');']);},],],

 

We still need to write the js implementation method update_status on the page. For details about how to load js at the bottom of the page, click the reference.

Related Article

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.