yii2 GridView常见操作,yii2gridview
yii2 GridView常见操作,yii2gridview
作者:白狼 出处:http://www.manks.top/article/yii2_gridview
本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
收集了网络上GridView出现的大部分问题做一个总结,希望有一个能帮助到你。
如果下面有没说到的GridView常见问题,下方留言,我会进行补充。
-
下拉搜索
-
日期格式化并实现日期可搜索
-
根据参数进行是否显示
-
链接可点击跳转
-
显示图片
-
html渲染
-
自定义按钮
-
设定宽度等样式
-
自定义字段
-
自定义行样式
-
增加按钮调用js操作
下拉搜索,我们先来看看预期的效果图
具体怎么实现喃?考虑到一张数据表要下拉效果的字段可能有很多个,我们先在其model中实现一个方法方便后续操作
<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> }
然后我们上代码看看具体怎么实现的下拉搜索
<?= 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>?>
像这样,我们就简单地实现了两个下拉效果,要实现筛选功能,在你的dataProvider自定添加该字段的搜索条件即可
日期格式化,我们先来看看效果图
这个我们分情况讨论
1、如果你的数据库字段created_at存的时间格式是date或者datetime,那很简单,gridview中直接输出该字段created_at即可,如上图中右侧所示
2、如果数据库存入的时间戳类型,如上图中左侧所示,则需要像下面这样进行输出
<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>,
以上展示了两种方式进行格式输出,都可以。但是,如果想要实现搜索的机制,如果你的数据库存入的是datetime型,很方便,dataProvider不用做修改,
代码如下
<span>$query</span>-><span>andFilterWhere([ </span><span>//</span><span> ......</span> 'created_at' => <span>$this</span>->created_at, <span>//</span><span> ......</span> ]);
如果你的数据库存入的是时间戳,
第一步,修改对应规则如下图所示
第二步,修改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>
这里做个小总结,建议使用datetime类型,个人觉得存时间戳甚是麻烦,如果你有好的建议,下方留言我们共同交流。
是否显示某列案例
我们举一个简单的案例
条件:有一个get形参数type
需求:仅且type的值等于1的时候,列name才显示,否则该列不显示
代码实现如下:
<span>[ </span>'attribute' => 'name', 'value' => <span>$model</span>->name, 'visible' => <span>intval</span>(Yii::<span>$app</span>->request->get('type')) == 1,<span> ]</span>,
实现方式也是很简单滴。
链接可点击跳转案例
这个跟接下来我们要说的html渲染的效果十分类似,这里要说的是列的属性值 format,具体都有哪些格式可查看文件 yii\i18n\Formatter.php,各种format都可以解决
<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>,
显示图片案例
同上,这里只需要指定format格式为image即可,format第二个参数可设定图片大小,可参考下面的代码
<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>,
html渲染案例
什么意思喃,举个例子,我们有一个字段,标记为title,但是这个title不一样,ta含有html标签,我们不想在页面上展示
title123
这种形式,我们想要title123以p标签的形式展示,代码可参考如下,只需要指定format为raw形式即可
<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>,
自定义按钮案例
往往列表页我们不想要删除按钮,想在增加一个比如获取xxx按钮,怎么搞呢?这里需要设置ActionColumn类,修改配置项template并在buttons项增加template里增加的get-xxx即可
<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>,
设定宽度案例
举个简单的例子,我们的title列,太长了,能不能给我先定下这一列的宽度?
答案:能。
请看示例:
<span>[ </span>'attribute' => 'title', 'value' => 'title', 'headerOptions' => ['width' => '100'],<span> ]</span>,
只需要指定配置项headerOptions即可。
自定义字段案例
啥时自定义?这里我们是指在表格里增加一列且数据库中不存在对应的列。假如我们新增一列 订单消费金额money且该表不存在该字段
<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需要有对应的样式实现,这里我们看一下页面的实际效果
增加按钮调用js操作案例
那边产品经理走过来了,小王呀,你这个修改状态的功能很频繁,每次都要先点进详情页才能修改,能不能我在列表页面上鼠标那么一点就成功修改了呢?
其实就是一个异步请求操作了当前行的状态嘛,我们来看看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请点击参考

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PyCharm is a very popular Python integrated development environment (IDE). It provides a wealth of functions and tools to make Python development more efficient and convenient. This article will introduce you to the basic operation methods of PyCharm and provide specific code examples to help readers quickly get started and become proficient in operating the tool. 1. Download and install PyCharm First, we need to go to the PyCharm official website (https://www.jetbrains.com/pyc

sudo (superuser execution) is a key command in Linux and Unix systems that allows ordinary users to run specific commands with root privileges. The function of sudo is mainly reflected in the following aspects: Providing permission control: sudo achieves strict control over system resources and sensitive operations by authorizing users to temporarily obtain superuser permissions. Ordinary users can only obtain temporary privileges through sudo when needed, and do not need to log in as superuser all the time. Improved security: By using sudo, you can avoid using the root account during routine operations. Using the root account for all operations may lead to unexpected system damage, as any mistaken or careless operation will have full permissions. and

LinuxDeploy operating steps and precautions LinuxDeploy is a powerful tool that can help users quickly deploy various Linux distributions on Android devices, allowing users to experience a complete Linux system on their mobile devices. This article will introduce the operating steps and precautions of LinuxDeploy in detail, and provide specific code examples to help readers better use this tool. Operation steps: Install LinuxDeploy: First, install

Presumably many users have several unused computers at home, and they have completely forgotten the power-on password because they have not been used for a long time, so they would like to know what to do if they forget the password? Then let’s take a look together. What to do if you forget to press F2 for win10 boot password? 1. Press the power button of the computer, and then press F2 when turning on the computer (different computer brands have different buttons to enter the BIOS). 2. In the bios interface, find the security option (the location may be different for different brands of computers). Usually in the settings menu at the top. 3. Then find the SupervisorPassword option and click it. 4. At this time, the user can see his password, and at the same time find the Enabled next to it and switch it to Dis.

Apple brought some Pro-exclusive hardware features to iPhone 15 Pro and 15 Pro Max, which attracted everyone’s attention. We're talking titanium frames, sleek designs, the new A17 Pro chipset, an exciting 5x telephoto lens, and more. Of all the bells and whistles added to the iPhone 15 Pro models, the action button remains a prominent and prominent feature. Needless to say, it is a useful addition to launching actions on your iPhone. That said, you could accidentally hold down the Action button and trigger the feature inadvertently. Frankly, it's annoying. To avoid this, you should disable the action button on iPhone 15 Pro and 15 Pro Max. let

With the popularity of smartphones, the screenshot function has become one of the essential skills for daily use of mobile phones. As one of Huawei's flagship mobile phones, Huawei Mate60Pro's screenshot function has naturally attracted much attention from users. Today, we will share the screenshot operation steps of Huawei Mate60Pro mobile phone, so that everyone can take screenshots more conveniently. First of all, Huawei Mate60Pro mobile phone provides a variety of screenshot methods, and you can choose the method that suits you according to your personal habits. The following is a detailed introduction to several commonly used interceptions:

Apple's iPhone 15 Pro and iPhone 15 Pro Max introduce a new programmable action button that replaces the traditional ring/silent switch above the volume buttons. Read on to learn what the Action button does and how to customize it. A new action button on Apple iPhone 15 Pro models replaces the traditional iPhone switch that activates Ring and Silent. By default, the new button will still activate both functions with a long press, but you can also have a long press perform a range of other functions, including quick access to the camera or flashlight, activating voice memos, focus mode, translation, and accessibility features like magnifier . You can also associate it with a single shortcut, opening up a ton of other possibilities

CSS web page scroll monitoring: monitor web page scroll events and perform corresponding operations. With the continuous development of front-end technology, the effects and interactions of web pages are becoming more and more rich and diverse. Among them, scroll monitoring is a common technology that can perform some special effects or operations based on the scroll position when the user scrolls the web page. Generally speaking, scroll monitoring can be implemented through JavaScript. However, in some cases, we can also achieve the effect of scroll monitoring through pure CSS. This article will introduce how to implement scrolling of web pages through CSS
