Yii2 related learning record, GridView widget usage and kartik-v/yii2-grid extension (v)

Source: Internet
Author: User

Now record the relevant contents of the GridView, is also obsessive-compulsive disorder, Yii2 the GridView although good, but the filter bar if some fields do not need, will not automatically merge into a row, of course, you can filter the bar instead, but at the top of their own to write some data to retrieve, but it is very troublesome, You have to plan your own style, write a search or something. Exactly when the search will retrieve the column and the title merge, see the kartik-v/yii2-grid can implement these functions, but also comes with the export of Excel, CSV and other data, so also by the way to try its function, call out their favorite style. Before using the kartik-v GridView, we still need to understand the function of the GridView Yii2, which is generally used as follows:

1, the YII default has four kinds of style columns, respectively for Data column (default), Action column (action), Checkbox column (selectable), Serial column (with serial number)

2. The title name will be automatically replaced with the corresponding Chinese according to the Attributelabels () method in the model. Of course, it can be defined by ' label ', while ' attribute ' specifies which field to sort by. The other looks like ' visible ' to hide the display, ' header ' shows the header content, ' headeroptions ' to define CSS or style styles, and so on.

[    ' label ' = ' You want the name ',    ' attribute ' + ' id ',// field can be sorted ]

3. Custom display pages and sort fields, if Searchmodel is used, it needs to be defined in the Searchmodel search method, otherwise it needs to be defined in the controller:

$dataProvider New Activedataprovider ([    $query,    ' pagination ' = =        [' pageSize ' + = 15 ,// if not defined, by default,    ' sort ' = = [' Attributes ' = ' + ' [' ID ']],// if defined, Can only be sorted by ID, otherwise all fields will be ]);

4, drop-down menu retrieval, like according to the drop-down menu to retrieve the user state, you need to first define the relevant method in the model, and then in the GridView processing:

//model, define a static methodConststatus_deleted = 0;ConstStatus_active = 10; Public Static functionGetzhstatus ($status=false){    $status _array= [        ' = ' and ' Please select ', Self::status_deleted=> ' Forbidden ', Self::status_active=> ' normal '    ]; return $status==false?$status _array: Arrayhelper::getvalue ($status _array,$status, ' unknown ');} //in the GridView[     ' attribute ' = ' status ', ' Filter ' =>html::activedropdownlist ($searchModel, ' status ', User::getzhstatus (), [' class ' = ' Form-control ']), ' value ' =function($data){        returnUser::getzhstatus ($data-status); },],

5, format time, there are several ways:

Method One: Similar to the above definition callback function

[    ' attribute ' = ' created_at ',    ' value ' =function($data) {         return Date (' y-m-d ',$data-created_at);      },]

Method Two: With the GridView format configuration

[    ' attribute ' = ' created_at ',    ' format ' =>[' Date ', ' php:y-m-d '],    ' value ' = ' Created_at ',],

Method Three: First configure your time format in config, otherwise it will be in English format, and then processed in the GridView.

// define your own time, money and other formats in common/config/main.php ' components ' and [    '         formatter ' = [ ' DateFormat ' = ' yyyy-mm-dd ',        ' DateTimeFormat ' and ' yyyy-mm-dd HH:mm:ss ',        ' decimalseparator ' = ', ',        ' thousandseparator ' + ',        ' currencycode ' = ' CNY ',    ],

Here's a quick way to write: "Attribute:format:label" (attribute: Format: label) in this format, click here for details on the API documentation. So we can do this: (if the above is defined, then method two can be directly ' format ' = ' date ' to display correctly)

' Created_at:date ',

6, display hyperlinks or pictures, is the method of the callback function, here with the hyperlink as an example, note that format needs to be ' raw ', do not format the results of any formatting, specific formatting aspects can point here to see.

[     ' attribute ' = ' id ',    ' value ' =function($model$key$index  $column) {        return html::a ($model->id,[' User/view ', ' id ' = = $model->id],[' class ' = ' Profile-link ', ' target ' = ' _blank ']);    },    ' format ' = ' and ' raw ',],

7, the association form display, this place directly to see the guide, point here to see, in short, if the management form is set up, Directly with similar order.name this can be directly displayed, if you want to retrieve the sort, you need to write this field in the Searchmodel rulers rule method and attributes attribute method. Add a Andfilterwhere search in the search method, and use the $query->joinwith associated field, $dataProvider->sort->attributes[] To add sorting, and so on.

8. Custom Action Column button,

[    ' class ' = ' Yii\grid\actioncolumn ',    ' header ' = ' operation ',    ' headeroptions ' =>[' width ' = > ' + ', '    template ' = ' {view} {update} ' {delete} {forbid} ',    ' buttons '        = ' = ' forbid ' = >function($url,$model) {            return Html::A (' <i class= "Glyphicon glyphicon-remove-circle" ></i> ", [' user/forbid ', ' id ' = = $model->id])             ;     ,]

The above is the use of the GridView Yii2 comes with. Again kartik-v/yii2-grid, official documents and demo of the comparison, it is more than the original form of several columns, such as editable column (editable), Radio column (radio box), etc. There are a number of other features, such as scrolling can be fixed title bar for easy viewing, you can total, export svn,excel and other formats. Here's a little bit:

PDF errors may be error after the installation is complete, as these associations are not yet installed, can be installed as prompted or you can configure the ' export ' =>false to cancel the export function, which will be configured in detail when exporting.

1, the overall structure such as:

2, the various parts of the very flexible display or hide, for example I do not want the header, but also want to show how many pages of this summary, you can put it in the before, you can set the following:

' panel ' = =    [' heading ' +false,// not    ' before ' = ' <div style = "margin-top:8px" >{summary}</div> ',// put in before, the front div is mainly to make it look good ],

Of course, the above requirements we can also be directly used panelheadingtemplate and panelbeforetemplate to reassemble, specifically to view the layout templates small chapters

3, some useful small settings

' Responsive ' =true,//Adaptive , default is True' Hover ' =true,//The color changes when the mouse moves up, the default is False' Floatheader ' =true,//when scrolling down, the title bar can be fixed, default to False' Showpagesummary ' =true,//Displays the statistics bar, which defaults to some of the settings in False//column' Columns ' = [    [        ' Class ' = ' \kartik\grid\checkboxcolumn ', ' rowselectedclass ' and ' gridview::type_info ', ' visible ' =true,//does not show, the code is not' Hidden ' =true,//hidden, Code Also, export CSV, etc. still exist' Hiddenfromexport ' =true,//Although displayed, it is ignored when exporting CSV' Pagesummary ' = ' total ',//can be a string, when True, auto-Total' Mergeheader ' =true,//Merge title and search bar],]

4, {Toggledata} settings, mainly used to display the paging or all the data display

' Toggledataoptions ' =[    ' maxCount ' = ' + ',// when more than 200, this button is hidden to avoid too much data causing loading problems    //' Mincount ' + 10,//when more than 10, click on the following prompt    number_format($dataProvider Gettotalcount ()). ' Data, OK to show all? ',// confirm when clicked ],

5, {Export} settings, can export excel,csv,pdf and other types of files, the following is the format of exporting CSV, if only the CSV is configured in Exportconfig, only the export CSV, if you want to export formats such as Excel, Need to be added in Exportconfig. When I export CSV here, regardless of setting the encoding is GBK or UTF, with excel2013 Open is Chinese garbled, and with sublime and other editors open then normal, (export Excel format is normal), have known this problem friend, trouble message advice.

' Export ' =[    ' fontawesome ' = ' fa fa-share-square-o ',//icons' Target ' = ' _blank ',//Open in New tab' Encoding ' = ' GBK ',//Coding], ' exportconfig ' =[GridView:: CSV = [        ' Label ' = ' export csv ', ' iconoptions ' and ' = ' ' class ' = ' text-primary ', ' showheader ' =true, ' showpagesummary ' =true, ' showfooter ' =true, ' showcaption ' =true, ' filename ' = ' user table '.Date("y-m-d"), ' alertmsg ' and ' = ' Are you sure you want to export the CSV format file? ' Options ' and ' = ' [            ' Title ' = ', '        ], ' mime ' = ' application/csv ', ' config ' = [            ' Coldelimiter ' and ', ', ' rowdelimiter ' = ' \ r \ n ',        ],    ],       ],

That's all there is to it. The style that I am also quite satisfied with: (the Kartik-v/yii2-grid style relies on bootstrap, which conflicts with the Adminlte table style, especially when merging the title bar and the search bar, the lower border of the merge becomes thicker, Try a lot of settings to make it all bold, and finally can only compromise, modify the default style of Kartik-v/yii2-grid Kv-merged-header, add this paragraph: $this->registercss (". kv-merged-header{border-bottom:1px solid #eee!important} "), barely looking past. )

Would like to continue to write down the beautification of alert,confirm and other pop-up boxes and automatically shut down what the extension and the code of bulk deletion, etc., but kartik-v/yii2-dialog this is the installation of the error. If you find any alternative, then add it. Write this way Firefox crashes two times, rewrite a good big piece of content, crying dead!

Yii2 related learning record, GridView widget usage and kartik-v/yii2-grid extension (v)

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.