浅析Yii2中GridView常见操作_PHP
Yii2
本文是小编给大家收集整理些有关网络上GridView出现的大部分问题,本文做一个总结特此分享到平台供大家参考。
如果下面有没说到的GridView常见问题,下方留言,我会进行补充。
下拉搜索
日期格式化并实现日期可搜索
根据参数进行是否显示
链接可点击跳转
显示图片
html渲染
自定义按钮
设定宽度等样式
自定义字段
自定义行样式
增加按钮调用js操作
yii2 GridView 下拉搜索实现案例教程
yii2 GridView 日期格式化并实现日期可搜索 案例
是否显示某列案例
我们举一个简单的案例
条件:有一个get形参数type
需求:仅且type的值等于1的时候,列name才显示,否则该列不显示
代码实现如下:
[ 'attribute' => 'name', 'value' => $model->name, 'visible' => intval(Yii::$app->request->get('type')) == 1, ],
实现方式也是很简单滴。
链接可点击跳转案例
这个跟接下来我们要说的html渲染的效果十分类似,这里要说的是列的属性值 format,具体都有哪些格式可查看文件 yii\i18n\Formatter.php,各种format都可以解决
[ 'attribute' => 'order_id', 'value' => function ($model) { return Html::a($model->order_id, "/order?id={$model->order_id}", ['target' => '_blank']); }, 'format' => 'raw', ],
显示图片案例
同上,这里只需要指定format格式为image即可,format第二个参数可设定图片大小,可参考下面的代码
[ 'label' => '头像', 'format' => [ 'image', [ 'width'=>'84', 'height'=>'84' ] ], 'value' => function ($model) { return $model->image; } ],
html渲染案例
什么意思喃,举个例子,我们有一个字段,标记为title,但是这个title不一样,ta含有html标签,我们不想在页面上展示
title123
这种形式,我们想要title123以p标签的形式展示,代码可参考如下,只需要指定format为raw形式即可
[ 'attribute' => 'title', 'value' => function ($model) { return Html::encode($model->title); }, 'format' => 'raw', ],
自定义按钮案例
往往列表页我们不想要删除按钮,想在增加一个比如获取xxx按钮,怎么搞呢?这里需要设置ActionColumn类,修改配置项template并在buttons项增加template里增加的get-xxx即可
[ 'class' => 'yii\grid\ActionColumn', 'template' => '{get-xxx} {view} {update}', 'header' => '操作', 'buttons' => [ 'get-xxx' => function ($url, $model, $key) { return Html::a('获取xxx', $url, ['title' => '获取xxx'] ); }, ], ],
设定宽度案例
举个简单的例子,我们的title列,太长了,能不能给我先定下这一列的宽度?
答案:能。
请看示例:
[ 'attribute' => 'title', 'value' => 'title', 'headerOptions' => ['width' => '100'], ],
只需要指定配置项headerOptions即可。
自定义字段案例
啥时自定义?这里我们是指在表格里增加一列且数据库中不存在对应的列。假如我们新增一列 订单消费金额money且该表不存在该字段
[ 'attribute' => '消费金额', 'value' => function ($model) { // 这里可以根据该表的其他字段进行关联获取 } ],
自定义行样式
有小伙伴说了,gii生成的这个gridview表格呀,行跟行的颜色不明显,看着难受,我滴乖乖,具体怎么难受咱们就不追究了。我们来看看怎么定义行样式
<?= GridView::widget([ // ...... 'dataProvider' => $dataProvider, 'rowOptions' => function($model, $key, $index, $grid) { return ['class' => $index % 2 ==0 ? 'label-red' : 'label-green']; }, // ...... ]); ?>
前面的操作我们都是依据列column的,这里因为是对行的控制,所以我们配置rowOptions要稍微注意一下。此外,自定义的label-red和label-green需要有对应的样式实现,这里我们看一下页面的实际效果
增加按钮调用js操作案例
那边产品经理走过来了,小王呀,你这个修改状态的功能很频繁,每次都要先点进详情页才能修改,能不能我在列表页面上鼠标那么一点就成功修改了呢?
其实就是一个异步请求操作了当前行的状态嘛,我们来看看gridview里面是怎么实现的。
[ 'class' => 'yii\grid\ActionColumn', 'header' => '操作', 'template' => '{view} {update} {update-status}', 'buttons' => [ 'update-status' => function ($url, $model, $key) { return Html::a('更新状态', 'javascript:;', ['onclick'=>'update_status(this, '.$model->id.');']); }, ], ],
我们需要在页面写js实现方法 update_status, 关于如何在页面底部加载js请点击参考
补充:GridView 小部件在开发中常用的功能及技巧。
数据网格或者说 GridView 小部件是Yii中最强大的部件之一。
它有一个属性名叫 dataProvider ,这个属性能够提供一个数据提供者的示例并且可以显示所提供的数据,即使用 yii\grid\GridView::columns 属性的一组列配置,在一个表格中渲染每一行数据。
例如,
use yii\grid\GridView; echo yii\grid\GridView::widget([ 'dataProvider' => $dataProvider, ]);
一、表格列
表格的列是通过 GridView 配置项中的 yii\grid\GridView::columns 属性配置的.
<?php use yii\grid\GridView; echo GridView::widget([ 'dataProvider' => $dataProvider, //表格列值搜索功能,注意一定要配合attribute才会显示 //$searchModel = new ArticleSearch(); 'filterModel' => $searchModel, //重新定义分页样式 'layout'=> '{items}<div class="text-right tooltip-demo">{pager}</div>', 'pager'=>[ //'options'=>['class'=>'hidden']//关闭分页 'firstPageLabel'=>"First", 'prevPageLabel'=>'Prev', 'nextPageLabel'=>'Next', 'lastPageLabel'=>'Last', ] 'columns' => [ ['class' => 'yii\grid\SerialColumn'],//序列号从1自增长 // 数据提供者中所含数据所定义的简单的列 // 使用的是模型的列的数据 'id', 'username', // 更复杂的列数据 [ 'class' => 'yii\grid\DataColumn', //由于是默认类型,可以省略 'value' => function ($data) { return $data->name; // 如果是数组数据则为 $data['name'] , 例如,使用 SqlDataProvider 的情形。 }, ], ['label'=>'标题','value' => 'title'], ['label'=>'文章内容','format' => 'html','value' => 'content'], [ 'label'=>'文章类别', /*'attribute' => 'cid',产生一个a标签,点击可排序*/ 'value' => 'cate.cname' //关联表 ], [ //动作列yii\grid\ActionColumn //用于显示一些动作按钮,如每一行的更新、删除操作。 'class' => 'yii\grid\ActionColumn', 'header' => '操作', 'template' => '{delete} {update}',//只需要展示删除和更新 'headerOptions' => ['width' => '240'], 'buttons' => [ 'delete' => function($url, $model, $key){ return Html::a('<i class="fa fa-ban"></i> 删除', ['del', 'id' => $key], [ 'class' => 'btn btn-default btn-xs', 'data' => ['confirm' => '你确定要删除文章吗?',] ] ); }, ], ], ], ]); ?>
1. 处理时间
数据列的主要配置项是 yii\grid\DataColumn::format 属性。
它的值默认是使用 \yii\i18n\Formatter 应用组件。
[ 'label'=>'更新日期', 'format' => ['date', 'php:Y-m-d'], 'value' => 'updated_at' ], //or [ //'attribute' => 'created_at', 'label'=>'更新时间', 'value'=>function($model){ return date('Y-m-d H:i:s',$model->created_at); }, 'headerOptions' => ['width' => '170'], ],
2. 处理图片
[ 'label'=>'封面图', 'format'=>'raw', 'value'=>function($m){ return Html::img($m->cover, ['class' => 'img-circle', 'width' => 30] ); } ],
3. 数据列有链接
[ 'attribute' => 'title', 'value' => function ($model, $key, $index, $column) { return Html::a($model->title, ['article/view', 'id' => $key]); }, 'format' => 'raw', ],
4. 数据列显示枚举值(男/女)
[ 'attribute' => 'sex', 'value'=>function ($model,$key,$index,$column){ return $model->sex==1?'男':'女'; }, //在搜索条件(过滤条件)中使用下拉框来搜索 'filter' => ['1'=>'男','0'=>'女'], //or 'filter' => Html::activeDropDownList($searchModel, 'sex',['1'=>'男','0'=>'女'], ['prompt'=>'全部'] ) ], [ 'label'=>'产品状态', 'attribute' => 'pro_name', 'value' => function ($model) { $state = [ '0' => '未发货', '1' => '已发货', '9' => '退货,已处理', ]; return $state[$model->pro_name]; }, 'headerOptions' => ['width' => '120'] ]
推荐阅读:
浅析Yii2中GridView常见操作
yii2 页面底部加载css和js的技巧
浅析Yii2 GridView 日期格式化并实现日期可搜索教程
浅析Yii2 GridView实现下拉搜索教程
以上内容是针对Yii2中GridView常见操作的全部介绍,希望对大家有所帮助!

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



Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...
