Related learning records of Yii2, use of the Gridview widget and kartik-v/yii2-grid extensions (v), yii2gridview
Now the relevant content of the Gridview is recorded. Although the Gridview in Yii2 is good, if some fields in the filter column are not needed, it will not be automatically merged into a row, of course, you can also filter out columns instead of writing some data to be retrieved at the top, but this is very troublesome. You need to plan the style and write the search information yourself. When the search merges the search bar and title, you can see that kartik-v/yii2-grid can achieve these functions, but also comes with export excel, csv and other data, so I also tried its function and pulled out my favorite style. Before using the Gridview of kartik-v, we still need to understand the function of the Gridview provided by Yii2. The common methods are as follows:
1. Yii has four types of columns by default, including Data column (default), Action column (operation), Checkbox column (optional), and Serial column (with Serial number)
2. The title name is automatically replaced with the corresponding Chinese name based on the attributeLabels () method in the Model. Of course, you can also use 'label' to define your own, while 'attribute' specifies which field to sort. Others are like 'visable' to hide the display, 'head' to show the content of the header, and 'headeroptions' to define css or style styles.
['Label' => 'name you want ', 'attribute' => 'id', // sortable fields]
3. Custom display pages and sorting fields. If searchModel is used, it must be defined in the search method of searchModel. Otherwise, it must be defined in the Controller:
$ DataProvider = new ActiveDataProvider (['query' => $ query, 'pagination' => ['pagesize' => 15, // if not defined, the default value is 20]. 'sort '=> ['bubuckets' => ['id'], // if defined, it can only be sorted by id; otherwise, all fields can be]);
4. drop-down menu retrieval. For example, to retrieve the user status based on the drop-down menu, you must first define the relevant methods in the model and then process them in the Gridview:
// In the Model, define a static method const STATUS_DELETED = 0; const STATUS_ACTIVE = 10; public static function getZhStatus ($ status = false) {$ status_array = [''=> 'select', self: STATUS_DELETED => 'disable', self: STATUS_ACTIVE => 'normal']; return $ status = false? $ Status_array: ArrayHelper: getValue ($ status_array, $ status, 'unknown ');} // ['attribute' => 'status ', 'filter' => Html: activeDropDownList ($ searchModel, 'status', User: getZhStatus (), ['class' => 'form-control']), 'value' => function ($ data) {return User: getZhStatus ($ data-> status) ;},],
5. There are several ways to format the time:
Method 1: similar to the previously defined callback function
[ 'attribute'=>'created_at', 'value'=>function($data){ return date('Y-m-d',$data->created_at); },]
Method 2: Use the format configuration that comes with the Gridview
[ 'attribute'=>'created_at', 'format'=>['date','php:Y-m-d'], 'value'=>'created_at',],
Method 3: Configure your time format in config. Otherwise, the time format will be in English and then be processed in the Gridview.
// In common/config/main. the 'components' => ['formatter '=> ['dateformat' => 'yyyy-MM-dd ', 'datetimeformat' => 'yyyy-MM-dd HH: mm: ss', 'decimalseparator' => ',', 'thousandseparator' => '', 'currencycode' => 'cny ',],],
Here we use a fast Writing Method: "attribute: format: label" (attribute: format: label). For details, click the api documentation here. So we can do this: (if the top part is defined, method 2 can be directly 'format' => 'date' to display it correctly)
'created_at:date',
6. Displaying hyperlinks or images is a callback function. Here, the hyperlink is used as an example. Note that the format must be 'Raw' and no formatting is performed on the result, for details about formatting, click here.
[ 'attribute'=>'id', 'value'=>function($model, $key, $index, $column){ return Html::a($model->id,['user/view','id'=>$model->id],['class' => 'profile-link','target'=>'_blank']); }, 'format' => 'raw',],
7. The associated form is displayed. For more information, see the Guide. Click here. In short, if the management form is set, directly use an order similar to order. name can be directly displayed and used. If you want to search for sorting, you must use the rulers rule method and attributes
This field is written to the attribute method. The search method adds the andFilterWhere retrieval, and associates the field with $ query-> joinWith, and $ dataProvider-> sort-> attributes [] to add sorting.
8. Custom Action Column button,
['Class' => 'yii \ grid \ actioncolumn', 'header' => 'operation', 'headeroptions' => ['width' => '123'], 'template' => '{view} {update} {delete} {forbid}', 'buttons' => ['forbid' => function ($ url, $ model) {return Html: a ('<I class = "glyphicon-remove-circle"> </I>', ['user/forbid ', 'id' => $ model-> id]);}],]
The preceding figure shows the usage of the Gridview provided by Yii2. Next let's talk about kartik-v/yii2-grid, the official documentation and demo is more comprehensive, it is more than the native of a few columns, such as Editable Column (Editable), Radio Column (single partition), and other functions, such as fixed title bars for viewing during scrolling, total, export svn, excel, and other formats. Let's talk about it a little bit:
After the installation is complete, a pdf error may be reported. Because these links are not yet installed, you can follow the prompts to install them or configure 'Port' => false to cancel the export function, detailed configuration will be given during the export below.
1. The overall structure is as follows:
2. The various parts in can be displayed or hidden flexibly. For example, if you do not want a header, but want to display the total number of pages of the summary, you can put it in before and set it as follows:
'Panel '=> ['heading' => false, // do not use 'before' =>' <div> // put it in before, the previous div mainly aims to make it look good.],
Of course, we can use panelHeadingTemplate and panelBeforeTemplate to re-assemble the above requirements. For details, refer to the Layout Templates section.。
3. Some useful small settings
'Responsion' => true, // adaptive. The default value is true 'hover '=> true. // when the mouse moves up, the color changes, the default value is false 'floathead' => true. // when scrolling down, the title bar can be fixed. The default value is false 'showpagesummary '=> true. // The Statistics column is displayed, the default value is false. // some settings in column: 'columns '=> [['class' =>' \ kartik \ grid \ CheckboxColumn ', 'rowselectedclass' => GridView: TYPE_INFO, 'visible '=> true, // do not display, and the Code does not have 'hided' => true, // hide, the Code also has, when exporting csv files, there are also 'dendenfromport' => true, // although it is displayed, 'pagesummary '=> 'Total' is ignored when exporting csv files. // It can be a string, if this parameter is set to true, 'mergeheader' => true, // merge titles and search columns],]
4. {toggleData} is set to display pages or all data.
'Toggledataoptions' => ['maxcount' => 200, // when there are more than 200 entries, this button is hidden to avoid loading problems due to too much data. // 'mincount' => 10, // when more than 10 messages are clicked, the following message is displayed: 'confirmmsg '=> 'Total '. number_format ($ dataProvider-> getTotalCount ()). 'Data entries. Are you sure you want to display all of them? ', // Click to confirm],
5. set {export} to export various types of files, such as excel, csv, and pdf. The following is the csv format for export. If only csv is configured in exportConfig, only exported csv files are displayed. If you want to export excel files or other formats, add them to exportConfig. When I export csv files here, no matter whether the encoding is gbk or utf, the files opened with excel2013 are garbled Chinese characters, and the files opened with the sublime editor are normal (the excel format is normal for export ), if you have any questions, please leave a message.
'Port' => ['fontawesome' => 'fa fa-share-square-O', // The icon 'target' => '_ blank ', // open 'encoding' => 'gbk' in the new tag, // encoding], 'exportconfig' => [GridView :: CSV => ['label' => 'export csv', 'iconoptions '=> ['class' => 'text-primary'], 'showhead' => true, 'showpagesummary '=> true, 'showfooter' => true, 'showcaption '=> true, 'filename' => 'user Table '. date ("Y-m-d"), 'alertmsg' => 'Are you sure you want to export a CSV file? ', 'Options' => ['title' => '',], 'mime' => 'application/csv ', 'config' => ['coldelimiter '=> ",", 'rowdelimiter' => "\ r \ n",],],
Basically so much, attached I still satisfied with the settings of the style :( kartik-v/yii2-grid style dependent on bootstrap, and adminlte table style conflict, especially when merging the title bar and the search bar, the bottom border of the merge will become coarse. I tried a lot of settings to make it all bold, and finally I had to compromise, modify the default style of the kv-merged-header for the kartik-v/yii2-grid, with this section added: $ this-> registerCss (". kv-merged-header {border-bottom: 1px solid # eee! Important} "), barely reading it .)
Originally want to continue to write beautify alert, confirm and other pop-up box and automatically close what extended and batch Delete Code again, but kartik-v/yii2-dialog this is the installation of non-stop error. Let's look for alternatives and try again later. On the way to writing this, Firefox crashed twice, rewritten a large part of the content, and cried!