search
HomeBackend DevelopmentPHP Tutorial浅析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表格呀,行跟行的颜色不明显,看着难受,我滴乖乖,具体怎么难受咱们就不追究了。我们来看看怎么定义行样式

<&#63;= GridView::widget([
// ......
'dataProvider' => $dataProvider,
'rowOptions' => function($model, $key, $index, $grid) {
return ['class' => $index % 2 ==0 &#63; 'label-red' : 'label-green'];
},
// ......
]); &#63;>

前面的操作我们都是依据列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 属性配置的.

<&#63;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' => '你确定要删除文章吗?',]
]
);
}, 
],
],

],
]);
&#63;>

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&#63;'男':'女'; 
},
//在搜索条件(过滤条件)中使用下拉框来搜索
'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常见操作的全部介绍,希望对大家有所帮助!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment