Author: Bai Lang Source: http://www.manks.top/article/yii2_gridview
The copyright of this article belongs to the author, and you are welcome to reprint it. However, this statement must be retained without the author's consent, and a link to the original text must be provided in an obvious position on the article page. Otherwise, we reserve the right to pursue legal liability.
We have collected most of the problems that occur with GridView on the Internet to make a summary. I hope one of them can help you.
If there are any frequently asked questions about GridView that are not mentioned below, leave a message below and I will add them.
Drop down search
Date formatting and date searchability
Whether to display based on parameters
The link can be clicked to jump
Show pictures
html rendering
Custom button
Set width and other styles
Custom fields
Customized row styles
Add button to call js operation
How to implement it specifically? Considering that a data table may have many fields that require drop-down effects, we first implement a method in its model to facilitate subsequent operations
<span> 1</span> <span>/*</span><span>* </span><span> 2</span> <span> * 下拉筛选 </span><span> 3</span> <span> * @column string 字段 </span><span> 4</span> <span> * @value mix 字段对应的值,不指定则返回字段数组 </span><span> 5</span> <span> * @return mix 返回某个值或者数组 </span><span> 6</span> <span>*/</span> <span> 7</span> <span>public</span> <span>static</span> <span>function</span> dropDown (<span>$column</span>, <span>$value</span> = <span>null</span><span>) </span><span> 8</span> <span>{ </span><span> 9</span> <span>$dropDownList</span> =<span> [ </span><span>10</span> 'is_delete'=><span> [ </span><span>11</span> '0'=>'显示', <span>12</span> '1'=>'删除', <span>13</span> ], <span>14</span> 'is_hot'=><span> [ </span><span>15</span> '0'=>'否', <span>16</span> '1'=>'是', <span>17</span> ], <span>18</span> <span>//</span><span>有新的字段要实现下拉规则,可像上面这样进行添加 </span><span>19</span> <span> // ......</span> <span>20</span> <span> ]; </span><span>21</span> <span>//</span><span>根据具体值显示对应的值</span> <span>22</span> <span>if</span> (<span>$value</span> !== <span>null</span><span>) </span><span>23</span> <span>return</span> <span>array_key_exists</span>(<span>$column</span>, <span>$dropDownList</span>) ? <span>$dropDownList</span>[<span>$column</span>][<span>$value</span>] : <span>false</span><span>; </span><span>24</span> <span>//</span><span>返回关联数组,用户下拉的filter实现</span> <span>25</span> <span>else</span> <span>26</span> <span>return</span> <span>array_key_exists</span>(<span>$column</span>, <span>$dropDownList</span>) ? <span>$dropDownList</span>[<span>$column</span>] : <span>false</span><span>; </span><span>27</span> }
Then let’s go to the code to see how to implement the drop-down search
<?= GridView::<span>widget([ </span>'dataProvider' => <span>$dataProvider</span>, 'columns' =><span> [ </span><span>//</span><span> ......</span> <span> [ </span>'attribute' => 'is_hot', 'value' => <span>function</span> (<span>$model</span><span>) { </span><span>return</span> Article::dropDown('is_hot', <span>$model</span>-><span>is_hot); }</span>, 'filter' => Article::dropDown('is_hot'),<span> ]</span>,<span> [ </span>'attribute' => 'is_delete', 'value' => <span>function</span> (<span>$model</span><span>) { </span><span>return</span> Article::dropDown('is_delete', <span>$model</span>-><span>is_delete); }</span>, 'filter' => Article::dropDown('is_delete'),<span> ]</span>, <span>//</span><span> ......</span> ],<span> ]); </span>?>
Like this, we have simply implemented two drop-down effects. To implement the filtering function, just add the search conditions for this field in your dataProvider.
We will discuss this on a case-by-case basis
1. If the time format stored in your database field created_at is date or datetime, it is very simple. Just output the field created_at directly in the gridview, as shown on the right side in the above figure
2. If the timestamp type stored in the database is as shown on the left in the above figure, it needs to be output as follows
<span>[ </span>'attribute' => 'created_at', 'value' => <span>function</span> (<span>$model</span><span>) { </span><span>return</span> <span>date</span>('Y-m-d H:i:s', <span>$model</span>-><span>created_at); }</span>,<span> ]</span>,<span> [ </span>'attribute' => 'created_at', 'format' => ['date', 'Y-m-d H:i:s'],<span> ]</span>,
The above shows two methods for format output, both are acceptable. However, if you want to implement a search mechanism, it is very convenient if your database is stored in datetime type. The dataProvider does not need to be modified,
The code is as follows
<span>$query</span>-><span>andFilterWhere([ </span><span>//</span><span> ......</span> 'created_at' => <span>$this</span>->created_at, <span>//</span><span> ......</span> ]);
If your database stores timestamps,
The first step is to modify the corresponding rules as shown below
In the second step, you can refer to the following code to modify the dataProvider
<span>//</span><span>我们搜索输入框中输入的格式一般是 2016-01-01 而非时间戳 //输出2016-01-01无非是想搜索这一天的数据,因此代码如下</span> <span>if</span> (<span>$this</span>-><span>created_at) { </span><span>$createdAt</span> = <span>strtotime</span>(<span>$this</span>-><span>created_at); </span><span>$createdAtEnd</span> = <span>$createdAt</span> + 24*3600<span>; </span><span>$query</span>->andWhere("created_at >= {<span>$createdAt</span>} AND created_at <= {<span>$createdAtEnd</span>}"<span>); }</span>
Here is a small summary. It is recommended to use the datetime type. Personally, I think it is very troublesome to save timestamps. If you have any good suggestions, please leave a message below and we can communicate together.
Let’s take a simple case
Condition: There is a get parameter type
Requirement: The column name will be displayed only when the value of type is equal to 1, otherwise the column will not be displayed
The code is implemented as follows:
<span>[ </span>'attribute' => 'name', 'value' => <span>$model</span>->name, 'visible' => <span>intval</span>(Yii::<span>$app</span>->request->get('type')) == 1,<span> ]</span>,
The implementation method is also very simple.
This is very similar to the html rendering effect we are going to talk about next. What we are going to talk about here is the attribute value format of the column. For specific formats, you can view the file yiii18nFormatter.php. Various formats can be solved
<span>[ </span>'attribute' => 'order_id', 'value' => <span>function</span> (<span>$model</span><span>) { </span><span>return</span> Html::a(<span>$model</span>->order_id, "/order?id={<span>$model</span>->order_id}", ['target' => '_blank'<span>]); }</span>, 'format' => 'raw',<span> ]</span>,
Same as above, here you only need to specify the format format as image. The second parameter of format can set the image size. You can refer to the code below
<span>[ </span>'label' => '头像', 'format' =><span> [ </span>'image',<span> [ </span>'width'=>'84', 'height'=>'84'<span> ] ]</span>, 'value' => <span>function</span> (<span>$model</span><span>) { </span><span>return</span> <span>$model</span>-><span>image; } ]</span>,
What does it mean? For example, we have a field marked title, but this title is different. It contains html tags. We don’t want to display the form
title123
on the page. We If you want title123 to be displayed in the form of a p tag, the code can be referenced as follows. You only need to specify the format as raw form
<span>[ </span>'attribute' => 'title', 'value' => <span>function</span> (<span>$model</span><span>) { </span><span>return</span> Html::encode(<span>$model</span>-><span>title); }</span>, 'format' => 'raw',<span> ]</span>,
Often we don’t want to delete the button on the list page, but want to add a button such as Get xxx. How to do it? Here you need to set up the ActionColumn class, modify the configuration item template and add the get-xxx added in the template to the buttons item
<span>[ </span>'class' => 'yii\grid\ActionColumn', 'template' => '{get-xxx} {view} {update}', 'header' => '操作', 'buttons' =><span> [ </span>'get-xxx' => <span>function</span> (<span>$url</span>, <span>$model</span>, <span>$key</span><span>) { </span><span>return</span> Html::a('获取xxx', <span>$url</span>, ['title' => '获取xxx'<span>] ); }</span>,<span> ]</span>,<span> ]</span>,
To give a simple example, our title column is too long. Can you set the width of this column for me first?
Answer: Yes.
See example:
<span>[ </span>'attribute' => 'title', 'value' => 'title', 'headerOptions' => ['width' => '100'],<span> ]</span>,
You only need to specify the configuration item headerOptions.
When to customize? Here we mean adding a column to the table and the corresponding column does not exist in the database. Suppose we add a new column of order consumption amount money and this field does not exist in the table
<span>[ </span>'attribute' => '消费金额', 'value' => <span>function</span> (<span>$model</span><span>) { </span><span>//</span><span> 这里可以根据该表的其他字段进行关联获取</span> <span> } ]</span>,
有小伙伴说了,gii生成的这个gridview表格呀,行跟行的颜色不明显,看着难受,我滴乖乖,具体怎么难受咱们就不追究了。我们来看看怎么定义行样式
<?= GridView::<span>widget([ </span><span>//</span><span> ......</span> 'dataProvider' => <span>$dataProvider</span>, 'rowOptions' => <span>function</span>(<span>$model</span>, <span>$key</span>, <span>$index</span>, <span>$grid</span><span>) { </span><span>return</span> ['class' => <span>$index</span> % 2 ==0 ? 'label-red' : 'label-green'<span>]; }</span>, <span>//</span><span> ......</span> ]); ?>
前面的操作我们都是依据列column的,这里因为是对行的控制,所以我们配置rowOptions要稍微注意一下。此外,自定义的label-red和label-green需要有对应的样式实现,这里我们看一下页面的实际效果
那边产品经理走过来了,小王呀,你这个修改状态的功能很频繁,每次都要先点进详情页才能修改,能不能我在列表页面上鼠标那么一点就成功修改了呢?
其实就是一个异步请求操作了当前行的状态嘛,我们来看看gridview里面是怎么实现的。
<span>[ </span>'class' => 'yii\grid\ActionColumn', 'header' => '操作', 'template' => '{view} {update} {update-status}', 'buttons' =><span> [ </span>'update-status' => <span>function</span> (<span>$url</span>, <span>$model</span>, <span>$key</span><span>) { </span><span>return</span> Html::a('更新状态', 'javascript:;', ['onclick'=>'update_status(this, '.<span>$model</span>->id.');']); },<span> ]</span>,<span> ]</span>,
还没完,我们还需要在页面写js实现方法 update_status, 关于如何在页面底部加载js请点击参考