Yii path to practice (1) @ View rendering
The View module is the V module of the MVC architecture in Yii. it is mainly responsible for displaying data, rendering template files, and displaying data content.
Basic concepts
MVC has a view folder in Yii, which stores the view file of the project and displays the data content.
-
First, a simple controller operation method is used to render and display a View. renderPartial () is called to render the View File. The first is the view file name, in the folder named by the controller under the views directory, the file name corresponds to the operation method; the second is the rendering view data, which must be an array.
-
This is a view script php, which displays some data from the controller, and some plug-ins can be called to complete some functions, such as data filtering.
-
Use the layout file processing view to create a layout file in the layout folder under the views directory.
-
Then, you can use render () to render the layout file. by default, the content data of the index View is embedded into the layout file in the form of $ content, and then displayed. of course, the second parameter of the render method is an array. you can use this array to render the data to the view and then display it.
-
In addition, multiple view files can be introduced in a view, which is also implemented through the render method.
The layout file data is displayed as $ content by default, and can be rendered to the view in the form of data blocks.
Common page interactions
Determine if else in Html:
Status = 1):?>Enabled
Disabled
Display some special buttons in Html:
$ DataProvider, 'filtermodel' => $ searchModel, 'column' => [['class' => 'II \ grid \ actioncolumn ', 'buttons' => ['layoutcontent' => function ($ url, $ model) {/*** @ var $ model Service */return Html :: a ('View service order information', Url: to (['jlerp-service-order/view', 'id' => $ model-> id]), ['class' => 'btn btn-success btn-xs ', 'target' =>' _ blank ']);}], 'template' => '{layoutContent}', 'options' => ['style' => 'Width: 100px '],],]);?>
Some buttons commonly used in Html
Preview homepage results
Note:
After you modify the homepage configuration, you can preview and view the results. The results are generated only after the modification is complete.
You can preview the layout based on the entered configuration version number.
The new homepage must be generated once.
Preview method
Enter the version number, click preview homepage effect to go to the preview effect page, and then:
In Firefox, press Ctrl + Shift + M to enter the responsive design drawing mode.
For Google browsers, press F12 and then Ctrl + Shift + M.
'Btn btn-success '])?>
'Btn btn-danger ', 'data-confirm' =>' are you sure the layout is effective? '])?>
Use of GirdView
This section describes some common use cases of GridView:
-
-
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
-
Batch delete using gridview
Drop-down search
Considering that there may be many drop-down fields in a data table, we first implement a method in its model to facilitate subsequent operations:
Public static function dropDown ($ column, $ value = null) {$ dropDownList = ['is _ delete' => ['0' => 'display ', '1' => 'Delete',], 'is _ hot '=> ['0' => 'no', '1' => 'yes',], // There are new fields to implement the drop-down rule, you can add as above // ......]; // display the corresponding value if ($ value! = Null) return array_key_exists ($ column, $ dropDownList )? $ DropDownList [$ column] [$ value]: false; // returns the associated array. the user-drop-down filter implements else return array_key_exists ($ column, $ dropDownList )? $ DropDownList [$ column]: false ;}
Then we can go to the code to see how to implement the drop-down search:
$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
This need to be discussed in different situations:
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, and 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 }");}
Whether to display a column
Here is a simple case:
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,],
Click to jump
This is very similar to html rendering. here we will talk about the attribute value format of the column. which formats can be used to view the file yiii18nFormatter. php? 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
Similarly, you only need to specify the format as image. The second parameter of format can be used to set the image size. See the following code:
['Label' => 'Avatar ', 'format' => ['image', ['width' => '84 ', 'height' => '84 '], 'value' => function ($ model) {return $ model-> image;}],
Html rendering
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',],
A custom button is usually a list page. We do not want to delete a button. how can we add a button like getting xxx? 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']) ;},],],
Set 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.
Custom field
What is custom? Here we add a column in the table and the database does not have a corresponding column.
Suppose we add a new column of order consumption amount money and the table does not have this field:
['Attribute' => 'consumption amount', 'value' => function ($ model) {// you can associate and obtain it based on other fields in the table.}],
Custom row
Some friends said that the row-to-row color of the gridview table generated by gii is not obvious and it looks uncomfortable. let's see how to define the row style:
$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
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.
Common Form View elements
Text box: textInput (); password box: passwordInput (); single keys: radio (), radioList (); check box: checkbox (), checkboxList (); drop-down box: dropDownList (); hidden Field: hiddenInput (); text field: textarea (['rows '=> 3]); file upload: fileInput (); submit button: submitButton (); reset button: resetButtun ();
['Test/post'], 'method' => 'post', 'id' = 'uploadform ',]);?> // Text input box
Field ($ model, 'Username')-> textInput (['maxlength' => 20])?> // Password input box
Field ($ model, 'password')-> passwordInput (['maxlength' => 20])?> // Single region
Field ($ model, 'sex')-> radioList (['1' => 'male', '0' => 'female])?> // Drop-down box
Field ($ model, 'edu')-> dropDownList (['1' => '', '2' => ''], ['proppt' => 'Select', 'Style' => 'width: 120px '])?> // File upload box
Field ($ model, 'file')-> fileInput ()?> // Check box
Field ($ model, 'hobby')-> checkboxList (['0' => 'Basketball ', '1' => 'soccer ', '2' => 'Badminton ', '3' => 'table tennis'])?> // Text input box
Field ($ model, 'info')-> textarea (['rows '=> 3])?>
Field ($ model, 'userid')-> hiddenInput (['value' => 3])?>
'Btn btn-primary ', 'name' => 'Submit-click'])?>
'Btn btn-primary ', 'name' => 'Submit-click'])?>