Common operations of GridView in Yii2

Source: Internet
Author: User
This article is a small Editor for you to collect and sort out most of the problems that occur in the common operations of the GridView in Yii2 on the network. This article makes a summary and is hereby shared with the network manager home platform for your reference.

This article is a small Editor for you to collect and sort out most of the problems that occur on the GridView on the network, this article makes a summary here to share with the platform for your reference.

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

Yii2 GridView drop-down search implementation case study

Yii2 GridView date formatting and implement date searchable case

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 and we do not want to display them on the page.

Title123

In this form, 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 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

Supplement: commonly used functions and skills in development of the GridView widget.

A data grid or a GridView widget is one of the most powerful components in Yii.

It has a property named dataProvider, which provides an example of a data provider and can display the provided data, that is, using yii \ grid \ GridView :: A group of column configurations in the columns attribute, rendering each row of data in a table.

For example,

use yii\grid\GridView;echo yii\grid\GridView::widget(['dataProvider' => $dataProvider,]);

I. table columns

The columns in the table are configured using the yii \ grid \ GridView: columns attribute in the GridView configuration item.

<? Phpuse yii \ grid \ GridView; echo GridView: widget (['dataprovider' => $ dataProvider, // table column value search function, be sure to use the attribute to display/$ searchModel = new ArticleSearch (); 'filtermodel' => $ searchModel, // redefine the paging style 'layout '=>' {items}

{Pager}

', 'Pager' => [// 'options' => ['class' => 'hidd'] // Close the pagination 'firstpagelabel' => "First ", 'prevpagelabel '=> 'prev', 'nextpagelabel' => 'next', 'lastpagelabel '=> 'Lala',] 'columns '=> [['class' => 'yii \ grid \ SerialColumn'], // the serial number increases from 1. // The simple column defined by the data contained in the data provider. // The data of the column in the model is 'Id', 'username ', // more complex column data ['class' => 'yii \ grid \ datacolumn', // because it is of the default type, you can omit 'value' => function ($ data) {return $ data-> name; // $ data ['name'] for array data, for example, Use SqlDataProvider.},], ['Label' => 'title', 'value' => 'title'], ['label' => 'article content', 'format' => 'html ', 'value' => 'content'], ['label' => 'Article class',/* 'attribute' => 'CID', generate a tag, click to sort */'value' => 'Cate. cname' // Associated table], [// action column yii \ grid \ ActionColumn // is used to display some action buttons, such as update and delete operations for each row. 'Class' => 'yii \ grid \ actioncolumn', 'header' => 'operation', 'template' => '{delete} {update }', // you only need to display the deletion and update 'headeroptions' => ['width' => '000000'], 'buttons' => ['delete' => function ($ url, $ model, $ key) {return Html: ('Delete ', ['Del', 'id' => $ key], ['class' => 'btn btn-default btn-xs ', 'data' => ['confirm' => 'are you sure you want to delete the article? ',]) ;},],]);?>

1. processing time

The main configuration item of the data column is the yii \ grid \ DataColumn: format attribute.
The default value is \ yii \ i18n \ Formatter application component.

['Label' => 'update date', 'format' => ['date', 'php: Y-m-d'], 'value' => 'updated _ at'], // or [// 'attribute' => 'created _ at', 'label' => 'update time ', 'value' => function ($ model) {return date ('Y-m-d H: I: S', $ model-> created_at );}, 'headeroptions' => ['width' => '2013'],],

2. process images

['Label' => 'Album art ', 'format' => 'raw', 'value' => function ($ m) {return Html :: img ($ m-> cover, ['class' => 'IMG-circle', 'width' => 30]);}],

3. data columns have links

['attribute' => 'title','value' => function ($model, $key, $index, $column) {return Html::a($model->title, ['article/view', 'id' => $key]);},'format' => 'raw',],

4. enumeration values in the data column (male/female)

['Attribute' => 'sex', 'value' => function ($ model, $ key, $ index, $ column) {return $ model-> sex = 1? 'Male': 'Female ';}, // use the drop-down box in the search condition (filter condition) to search for 'filter' => ['1' => 'male ', '0' => 'female '], // or 'filter' => Html: activeDropDownList ($ searchModel, 'sex', ['1' => 'male ', '0' => 'female '], ['propt' => 'all'])], ['label' => 'product status ', 'attribute' => 'Pro _ name', 'value' => function ($ model) {$ state = ['0' => 'undeliverable ', '1' => 'deliverable ', '9' => 'Return, handled',]; return $ state [$ model-> pro_name];}, 'headeroptions' => ['width' => '123']

Recommended reading:

Common operations of GridView in Yii2

Tips for loading css and js at the bottom of the yii2 page

Analysis on how to format and implement date searchable in Yii2 GridView

Analysis of Yii2 GridView implementation drop-down search tutorial

The above content is a full description of common operations on the GridView in Yii2. I hope it will help you!

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.