search
HomeBackend DevelopmentPHP TutorialYii 的修行之路(一)@View 视图渲染

简述

View模块是Yii中的MVC架构的V板块,主要负责数据的展示,渲染模板文件,展示数据内容。

基本概念

MVC在Yii里面有一个Views文件夹,里面存放的是项目的视图文件,负责展示数据内容。

  1. 首先这里是一个简单的控制器操作方法实现一个视图的渲染展示,调用renderPartial()来渲染视图文件,第一个是视图文件名,存在在views目录下的以控制器命名的文件夹下,文件名字与操作方法相对应;第二个则是渲染视图的数据,必须是一个数组。

  2. 这是一个视图脚本php,里面是展示一些控制器传来的数据,还可以调用一些插件完成一些功能,比如数据过滤等等。

  3. 利用布局文件处理视图,首先在views目录下的layout文件夹下创建一个布局文件,名字自拟。

  4. 然后可以利用render()的方法把布局文件渲染显示出来,而index视图的内容数据默认以$content的形式嵌入到布局文件,然后显示出来,当然,在render方法的第二个参数是一个数组,可以利用这个数组把数据渲染到视图上,然后展示出来。

  5. 此外在一个视图中还可以引入多个视图文件,也是通过render方法实现。

布局文件的数据默认以$content显示,也可以用数据块的形式渲染到视图上。

常见的页面交互

在Html上作 if else 的判断:

<?php if ($user->status == 1): ?>    <td class="td-status"><span class="label label-success radius">已启用</span></td><?php else: ?>    <td class="td-status"><span class="label label-success radius">已禁用</span></td><?php endif; ?>

在Html上显示一些特殊按钮:

    <?= GridView::widget([        'dataProvider' => $dataProvider,        'filterModel' => $searchModel,        'columns' => [            [                'class' => 'yii\grid\ActionColumn',                'buttons' => [                    'layoutContent' => function ($url, $model){                        /**                         * @var $model Service                         */                        return Html::a('查看服务单信息', Url::to(['jlerp-service-order/view', 'id' => $model->id]), [                            'class' => 'btn btn-success btn-xs', 'target' => '__blank'                        ]);                    }                ],                'template' => '{layoutContent}',                'options' => [                    'style' => 'width:100px'                ],            ]        ],    ]); ?>

一些在Html上常用的摁钮实现

    <div id="confirm-form">        <input type="text" id="version" name="version" placeholder="输入配置版本号">        <button onclick="confirm()" id='confirm-index' class='btn btn-info' type="submit">预览首页效果</button>    </div>    <br>    <div>        <p><font color=red>注意</font></p>        <p>每次修改完首页配置后,先预览查看效果,没问题后才确认生成。</p>        <p>可以根据输入的配置版本号预览查看相应的布局效果。</p>        <p><strong>必须要确认生成一次,才会正式生成新首页。</strong></p>    </div>    <div>        <p><font color=red>预览方法</font></p>        <p>输入版本号,点击预览首页效果,进入预览效果页,然后:</p>        <p>如果是火狐浏览器,按Ctrl+Shift+M进入响应式设计图模式。</p>        <p>如果是谷歌浏览器,按F12,再按Ctrl+Shift+M。</p>    </div>    <hr>    <p>        <?= Html::a('创建布局配置', ['create'], ['class' => 'btn btn-success']) ?>        <?= Html::a('确认布局生效', ['build-index'], ['class' => 'btn btn-danger', 'data-confirm' => '确认布局生效?']) ?>    </p>

GirdView的使用

介绍一些 GridView 常见的使用案例:

    • 下拉搜索

    • 日期格式化并实现日期可搜索

    • 根据参数进行是否显示

    • 链接可点击跳转

    • 显示图片

    • html渲染

    • 自定义按钮

    • 设定宽度等样式

    • 自定义字段

    • 自定义行样式

    • 增加按钮调用js操作

    • 利用gridview实现批量删除

下拉搜索

具体考虑到一张数据表要下拉效果的字段可能有很多个,我们先在其model中实现一个方法方便后续操作:

public static function dropDown ($column, $value = null) {    $dropDownList = [        'is_delete'=> [            '0'=>'显示',            '1'=>'删除',        ],        'is_hot'=> [            '0'=>'否',            '1'=>'是',        ],        //有新的字段要实现下拉规则,可像上面这样进行添加        // ......    ];    //根据具体值显示对应的值    if ($value !== null)         return array_key_exists($column, $dropDownList) ? $dropDownList[$column][$value] : false;    //返回关联数组,用户下拉的filter实现    else        return array_key_exists($column, $dropDownList) ? $dropDownList[$column] : false;}

然后我们上代码看看具体怎么实现的下拉搜索:

<?= GridView::widget([    'dataProvider' => $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'),        ],        // ......    ],]); ?>

像这样,我们就简单地实现了两个下拉效果,要实现筛选功能,在你的dataProvider自定添加该字段的搜索条件即可

日期格式化

这个需要分情况讨论:

1、如果你的数据库字段created_at存的时间格式是date或者datetime,那很简单,gridview中直接输出该字段created_at即可,如上图中右侧所示

2、如果数据库存入的时间戳类型,如上图中左侧所示,则需要像下面这样进行输出:

[    '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'],],

以上展示了两种方式进行格式输出,都可以。

但是,如果想要实现搜索的机制,如果你的数据库存入的是datetime型,很方便,dataProvider不用做修改,代码如下:

$query->andFilterWhere([    // ......    'created_at' => $this->created_at,    // ......]);

如果你的数据库存入的是时间戳,

第一步,修改对应规则如下图所示。

第二步,修改dataProvider可参考如下代码:

//我们搜索输入框中输入的格式一般是 2016-01-01 而非时间戳//输出2016-01-01无非是想搜索这一天的数据,因此代码如下if ($this->created_at) {    $createdAt = strtotime($this->created_at);    $createdAtEnd = $createdAt + 24*3600;    $query->andWhere("created_at >= {$createdAt} AND created_at <= {$createdAtEnd}");}

是否显示某列

举一个简单的案例:

条件:有一个 get 型参数type

需求:仅且 type 的值等于1的时候,列 name 才显示,否则该列不显示。

代码实现如下:

[    'attribute' => 'name',    'value' => $model->name,    'visible' => intval(Yii::$app->request->get('type')) == 1,],

链接可点击跳转

这个跟 html 渲染的效果十分类似,这里要说的是列的属性值 format,具体都有哪些格式可查看文件 yiii18nFormatter.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。

常见的 Form 表单视图元素

文本框:textInput();密码框:passwordInput();单选框:radio(),radioList();复选框:checkbox(),checkboxList();下拉框:dropDownList();隐藏域:hiddenInput();文本域:textarea(['rows'=>3]);文件上传:fileInput();提交按钮:submitButton();重置按钮:resetButtun();
<?php $form= ActiveForm::begin(['action'=> ['test/post'],'method'=>'post','id'='uploadform', ]); ?>// 文本输入框<?echo$form->field($model,'username')->textInput(['maxlength'=>20])?>// 密码输入框<?echo$form->field($model,'password')->passwordInput(['maxlength'=>20])?>// 单选框<?echo$form->field($model,'sex')->radioList(['1'=>'男','0'=>'女'])?>// 下拉选择框<?echo$form->field($model,'edu')->dropDownList(['1'=>'大学','2'=>'高中'], ['prompt'=>'请选择','style'=>'width:120px'])?>// 文件上传框<?echo$form->field($model,'file')->fileInput()?>// 复选框<?echo$form->field($model,'hobby')->checkboxList(['0'=>'篮球','1'=>'足球','2'=>'羽毛球','3'=>'乒乓球'])?>// 文本输入框<?echo$form->field($model,'info')->textarea(['rows'=>3])?><?echo$form->field($model,'userid')->hiddenInput(['value'=>3])?><?echoHtml::submitButton('提交', ['class'=>'btn btn-primary','name'=>'submit-button'])?><?echoHtml::resetButton('重置', ['class'=>'btn btn-primary','name'=>'submit-button'])?><?php ActiveForm::end(); ?>
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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools