Home php教程 php手册 PHP的Yii框架的基本使用示例

PHP的Yii框架的基本使用示例

Jun 06, 2016 pm 07:46 PM
use Basic frame Example

这篇文章主要介绍了PHP的Yii框架的基本使用示例,包括触发JS和添加关联表等操作,需要的朋友可以参考下

在 Yii 自动生成的代码里,我们总能在 admin 的界面看到 CGridView 的身影。这是一个很好用的展示数据的表格控件,用的好可以明显地加快开发进度。下面就让我们来探索一下 CGridView 的基本使用吧:

     简单起见,我们的代码就用 Yii demo 中的 blog 例子来做修改。首先,这是修改后的部分 Mysql 语句:

drop table if exists `tbl_user`; CREATE TABLE tbl_user ( `user_id` INTEGER NOT NULL AUTO_INCREMENT comment '主键', `username` VARCHAR(128) NOT NULL comment '用户名', `nickname` VARCHAR(128) NOT NULL comment '昵称', `password` VARCHAR(128) NOT NULL comment '密码', `email` VARCHAR(128) NOT NULL comment '邮箱', `is_delete` tinyint not null default 0 comment '删除标志', unique key(`username`), primary key (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 comment='用户表'; drop table if exists `tbl_post`; CREATE TABLE tbl_post ( `post_id` INTEGER NOT NULL AUTO_INCREMENT comment '主键', `title` VARCHAR(128) NOT NULL comment '标题', `content` TEXT NOT NULL comment '文章内容', `tags` TEXT comment '标签', `status` INTEGER NOT NULL comment '状态,,0 = 草稿,1 = 审核通过,-1 = 审核不通过,2 = 发布', `create_time` INTEGER comment '创建时间', `update_time` INTEGER comment '更新时间', `author_id` INTEGER NOT NULL comment '作者', `is_delete` tinyint not null default 0 comment '删除标志', CONSTRAINT `post_ibfk_1` FOREIGN KEY (author_id) REFERENCES tbl_user (`user_id`) ON DELETE CASCADE ON UPDATE RESTRICT, primary key (`post_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 comment='日志表';

    两个表一个存储作者信息一个存储日志,其中日志有一个外键关联到 user。两个表里面的 is_delete 字段是标志该条记录是否被删除,0 为未删除,1 为已删除。让我们看一下用 gii 生成的 Post 类的 relation 方法:

/** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'comments' => array(self::HAS_MANY, 'Comment', 'post_id'), 'author' => array(self::BELONGS_TO, 'User', 'author_id'), ); }

    其中的 author 外键作为 BELONGS_TO 关系存在,符合我们的预期。
    说了这么多,看看自动生成的 Post 中 admin.php 里 CGridView 的代码吧:

widget('zii.widgets.grid.CGridView', array( 'id'=>'post-grid', 'dataProvider'=>$model->search(), 'filter'=>$model, 'columns'=>array( 'post_id', 'title', 'content', 'tags', 'status', 'create_time', 'update_time', 'author_id', 'is_delete', array( 'class'=>'CButtonColumn', ), ), )); ?>

    看!虽然我们什么都没写,但这就是这个控件的最基础使用了。dataProvider 是由 model 里面的 search 函数提供的数据,filter...暂时看不出这里的作用,columns 控制展示的每一列,其中最后一项的 CButtonColumn 向我们展示了三个按钮,分别是 查看  更新 和 删除。
    接下来我们一点点地改造.

用 CGridView 展示我们真正要的数据形式:
    很多时候,数据库里的东西不适合直接展示给用户看,需要我们进行一定的处理之后才适合阅读。但在这里不经修改的话 CGridView 只会把数据库的值原封不动地呈现,所以,我们应该在相应的字段进行修改。比如 is_delete 字段,数据库里存放的是 0 和 1,但是在这里阅读就不太好了,我们应该改成 1 展示 '是' ,0展示 '否'。看看下面的代码,我们用了一个 array,两个键分别是 name 和 value,name 对应的要填写该 model 拥有的字段,而 value 是你想展示的数据,这里可以写成一个 php 语句,作为可以执行的代码。看到这里,是不是觉得对这个 value 我们可以做很多东西?有的同学可能要问,如果我想执行的代码很长,难道都写在 value 里面?。。。我说同学,你不会在其他地方写成一个函数然后在这里调用它吗??

widget('zii.widgets.grid.CGridView', array( 'id'=>'post-grid', 'dataProvider'=>$model->search(), 'filter'=>$model, 'columns'=>array( 'post_id', 'title', 'content', 'tags', 'status', 'create_time', 'update_time', 'author_id', 'is_delete', array( 'name'=>'is_delete', 'value'=>'is_delete?"是":"否"' //value 是可以执行 php 语句的哦 ) array( 'class'=>'CButtonColumn', ), ), )); ?>

     除此之外,还有一些常用的选项,都可以在 array 里面填写,下面是比较常见的使用方式(其他部分代码省略):

array( 'name'=>'is_delete', 'value'=>'is_delete?"是":"否"' //value 是可以执行 php 语句的哦 'filter' => array(0=>'否',1=>'是'), //自己定义搜索过滤的方式,这里为 是 和 否 的下拉菜单 'htmlOptions'=>array('class'=>'delete'), //可以定义 html 选项,这里是定义了带一个 delete 的类 ),

     上面我们用 name 的话那是 model 里原来就有的字段,如果我们想展示自己定义的新内容呢,用 header :

array( 'header'=>'备注', 'value'=> 'display your data' ),

添加 CCheckBoxColumn :
    有时也许我们会需要一个复选框,来对每一行进行选择,这时,我们可以增加一列,用 CCheckBoxColumn 类:

widget('zii.widgets.grid.CGridView', array( 'id'=>'post-grid', 'dataProvider'=>$model->search(), 'filter'=>$model, 'columns'=>array( array( 'selectableRows' => 2, //允许多选,改为 0 时代表不允许修改,1 的话为单选 'class' => 'CCheckBoxColumn',//复选框 'headerHtmlOptions' => array('width'=>'18px'),//头部的 html 选项 'checkBoxHtmlOptions' => array('name' => 'myname','class'=>'myclass'), //复选框的 html 选项 ), 'post_id', 'title', 'content', 'tags', 'status', 'create_time', 'update_time', 'author_id', 'is_delete', array( 'name'=>'is_delete', 'value'=>'is_delete?"是":"否"', //value 是可以执行 php 语句的哦 'filter' => array(0=>'否',1=>'是'), //自己定义搜索过滤的方式,这里为 是 和 否 的下拉菜单 'htmlOptions'=>array('class'=>'delete'), //可以定义 html 选项,这里是定义了带一个 delete 的类 ), array( 'class'=>'CButtonColumn', ), ), ));

修改ButtonColumn:
   注意到列表每一项的最后三个小图标吗?不需要的话当然是直接删了,那要是只要其中某几个呢?可以加一个 template 参数:

array( 'class'=>'ButtonColumn', 'template'=>"{view} {update}", ),

    也可以自定义按钮:

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
How to evaluate the cost-effectiveness of commercial support for Java frameworks How to evaluate the cost-effectiveness of commercial support for Java frameworks Jun 05, 2024 pm 05:25 PM

Evaluating the cost/performance of commercial support for a Java framework involves the following steps: Determine the required level of assurance and service level agreement (SLA) guarantees. The experience and expertise of the research support team. Consider additional services such as upgrades, troubleshooting, and performance optimization. Weigh business support costs against risk mitigation and increased efficiency.

What is Bitget Launchpool? How to use Bitget Launchpool? What is Bitget Launchpool? How to use Bitget Launchpool? Jun 07, 2024 pm 12:06 PM

BitgetLaunchpool is a dynamic platform designed for all cryptocurrency enthusiasts. BitgetLaunchpool stands out with its unique offering. Here, you can stake your tokens to unlock more rewards, including airdrops, high returns, and a generous prize pool exclusive to early participants. What is BitgetLaunchpool? BitgetLaunchpool is a cryptocurrency platform where tokens can be staked and earned with user-friendly terms and conditions. By investing BGB or other tokens in Launchpool, users have the opportunity to receive free airdrops, earnings and participate in generous bonus pools. The income from pledged assets is calculated within T+1 hours, and the rewards are based on

How does the learning curve of PHP frameworks compare to other language frameworks? How does the learning curve of PHP frameworks compare to other language frameworks? Jun 06, 2024 pm 12:41 PM

The learning curve of a PHP framework depends on language proficiency, framework complexity, documentation quality, and community support. The learning curve of PHP frameworks is higher when compared to Python frameworks and lower when compared to Ruby frameworks. Compared to Java frameworks, PHP frameworks have a moderate learning curve but a shorter time to get started.

Performance comparison of Java frameworks Performance comparison of Java frameworks Jun 04, 2024 pm 03:56 PM

According to benchmarks, for small, high-performance applications, Quarkus (fast startup, low memory) or Micronaut (TechEmpower excellent) are ideal choices. SpringBoot is suitable for large, full-stack applications, but has slightly slower startup times and memory usage.

How do the lightweight options of PHP frameworks affect application performance? How do the lightweight options of PHP frameworks affect application performance? Jun 06, 2024 am 10:53 AM

The lightweight PHP framework improves application performance through small size and low resource consumption. Its features include: small size, fast startup, low memory usage, improved response speed and throughput, and reduced resource consumption. Practical case: SlimFramework creates REST API, only 500KB, high responsiveness and high throughput

Golang framework documentation best practices Golang framework documentation best practices Jun 04, 2024 pm 05:00 PM

Writing clear and comprehensive documentation is crucial for the Golang framework. Best practices include following an established documentation style, such as Google's Go Coding Style Guide. Use a clear organizational structure, including headings, subheadings, and lists, and provide navigation. Provides comprehensive and accurate information, including getting started guides, API references, and concepts. Use code examples to illustrate concepts and usage. Keep documentation updated, track changes and document new features. Provide support and community resources such as GitHub issues and forums. Create practical examples, such as API documentation.

How to choose the best golang framework for different application scenarios How to choose the best golang framework for different application scenarios Jun 05, 2024 pm 04:05 PM

Choose the best Go framework based on application scenarios: consider application type, language features, performance requirements, and ecosystem. Common Go frameworks: Gin (Web application), Echo (Web service), Fiber (high throughput), gorm (ORM), fasthttp (speed). Practical case: building REST API (Fiber) and interacting with the database (gorm). Choose a framework: choose fasthttp for key performance, Gin/Echo for flexible web applications, and gorm for database interaction.

Java Framework Learning Roadmap: Best Practices in Different Domains Java Framework Learning Roadmap: Best Practices in Different Domains Jun 05, 2024 pm 08:53 PM

Java framework learning roadmap for different fields: Web development: SpringBoot and PlayFramework. Persistence layer: Hibernate and JPA. Server-side reactive programming: ReactorCore and SpringWebFlux. Real-time computing: ApacheStorm and ApacheSpark. Cloud Computing: AWS SDK for Java and Google Cloud Java.

See all articles