Table of Contents
Basic usage examples of PHP's Yii framework, yii framework examples
Home Backend Development PHP Tutorial Basic usage examples of PHP's Yii framework, yii framework examples_PHP tutorial

Basic usage examples of PHP's Yii framework, yii framework examples_PHP tutorial

Jul 13, 2016 am 09:44 AM
php yii

Basic usage examples of PHP's Yii framework, yii framework examples

In the code automatically generated by Yii, we can always see CGridView in the admin interface. This is a very useful table control for displaying data. If used well, it can significantly speed up the development progress. Let’s explore the basic use of CGridView:

For the sake of simplicity, our code will be modified using the blog example in Yii demo. First, here is the modified partial Mysql statement:

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='日志表'; 

Copy after login

Two tables, one storing author information and the other storing logs, where the logs have a foreign key associated with user. The is_delete field in the two tables marks whether the record has been deleted, 0 means not deleted, and 1 means deleted. Let's take a look at the relation method of the Post class generated with gii:

/** 
 * @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'), 
  ); 
} 
Copy after login
Copy after login

The author foreign key exists as a BELONGS_TO relationship, which is in line with our expectations.
Having said so much, let’s take a look at the code of CGridView in admin.php in the automatically generated Post:

<&#63;php $this->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', 
    ), 
  ), 
)); &#63;> 
Copy after login

Look! Although we haven't written anything, this is the most basic use of this control. dataProvider is the data provided by the search function in the model, filter... I can't see the role here for the time being. Columns controls each column displayed. The last item of CButtonColumn shows us three buttons, namely View Update and delete.
Next we will transform it bit by bit.

Use CGridView to display the data form we really want:
Many times, the things in the database are not suitable for displaying directly to users. We need to perform certain processing before they are suitable for reading. But without modification here, CGridView will only present the database value unchanged, so we should modify it in the corresponding field. For example, in the is_delete field, 0 and 1 are stored in the database, but it is not very good to read here. We should change it to 1 to display 'yes' and 0 to display 'no'. Take a look at the code below. We use an array. The two keys are name and value. Name corresponds to the fields owned by the model, and value is the data you want to display. It can be written as a php statement as code executed. Seeing this, do you think we can do a lot with this value? Some students may ask, if the code I want to execute is very long, is it all written in value? . . . I said classmate, wouldn’t you write a function somewhere else and then call it here? ?

<&#63;php $this->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&#63;"是":"否"' //value 是可以执行 php 语句的哦 
    ) 
    array( 
      'class'=>'CButtonColumn', 
    ), 
  ), 
)); &#63;> 
Copy after login

In addition, there are some commonly used options, which can be filled in the array. The following is the more common usage (other parts of the code are omitted):

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

If we use name above, it is an existing field in the model. If we want to display new content defined by ourselves, use header:

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

Copy after login

Add CCheckBoxColumn:
Sometimes we may need a check box to select each row. In this case, we can add a column and use the CCheckBoxColumn class:

<&#63;php $this->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&#63;"是":"否"', //value 是可以执行 php 语句的哦 
      'filter' => array(0=>'否',1=>'是'), //自己定义搜索过滤的方式,这里为 是 和 否 的下拉菜单 
      'htmlOptions'=>array('class'=>'delete'), //可以定义 html 选项,这里是定义了带一个 delete 的类 
    ), 
    array( 
      'class'=>'CButtonColumn', 
    ), 
  ), 
));  

Copy after login

Modify ButtonColumn:
Notice the last three little icons of each item in the list? Of course, if you don’t need them, just delete them directly. But what if you only want a few of them? You can add a template parameter:

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

You can also customize the button:

array( 
  'class'=>'ButtonColumn', 
  'template'=>"{view} {update} {print}", 
  'buttons'=>array( 
      'print'=>array( 
          'label'=>'打印', 
          'url'=>'Yii::app()->controller->createUrl("print", array("id"=>$data->post_id))', 
          'options'=>array("target"=>"_blank"), 
        ), 
      ), 
    ), 

Copy after login

Javascript triggered on refresh:
If you want to trigger some Javascript after each search, Yii also provides this option. You just need to write it as a function and set afterAjaxUpdate. Remember that this is only called after the ajax request is completed. If you want to If it is called as soon as the loading is completed, additional Javascript

needs to be added to the page.
  $js = <<<_JS_ 
function(){ 
  alert('The ajax finish'); 
 
} 
_JS_; 
 
$this->widget('zii.widgets.grid.CGridView', array( 
  'id'=>'post-grid', 
  'dataProvider'=>$model->search(), 
  'filter'=>$model, 
  'afterAjaxUpdate'=>$js, //看这里,ajax 之后调用的 javascript 在这里.... 
  'columns'=>array( 
    array( 
      'selectableRows' => 2, //允许多选,改为 0 时代表不允许修改,1 的话为单选 
      'class' => 'CCheckBoxColumn',//复选框 
      'headerHtmlOptions' => array('width'=>'18px'), 
      'checkBoxHtmlOptions' => array('name' => 'myname','class'=>'myclass'), 
    ), 
    .... 
Copy after login

Add association table related field search:
First of all, we are only talking about "one-to-many" related search here. First of all, don't forget our database. If you forget, please click here: Here, you can see that there is a foreign key in tbl_post Associated with the tbl_user table to find author-related information. After building the database, take a look at the POST Model of the Yii code we generated. The realtion inside is as follows (ignore the comment):

/** 
 * @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'), 
  ); 
} 
Copy after login
Copy after login

You can see that the POST and USER tables can be accessed through the author key, for example: $model->author->nickname, and here is the BELONGS_TO relationship.
Having said so much, what exactly are our needs? ....

The product manager pushed up his glasses: "We want to add a function to the backend management interface of the log, which allows you to search for corresponding articles by author name. This is urgent and will be completed tonight."

淡定淡定,不就是改需求吗。忽略进度要求,我们研究一下究竟要做什么。
其实很简单的,不就是在 POST 的 admin 界面中增加一列作者名称,然后可以通过作者名的 模糊搜索 去找到对应日志吗?看看代码,要是通过 作者 id 去搜索不就简单了吗?不过这样确实不太友好...如果是展示作者名字而已不也是很简单吗?加一个 header 然后 value 是 $data->author->username, 问题是这样只能展示,不能进行搜索...哎,好苦恼。
淡定淡定,不就是多个搜索吗?来,让我告诉你怎么做。

首先,我们进入 POST 的 model,在一开始的地方添加一个属性:

class Post extends CActiveRecord 
{ 
  public $name; //添加一个 public 属性,代表作者名 
  然后改一下 Model 里面 search 的代码,改动部分都已经加了注释:

public function search() 
{ 
  // @todo Please modify the following code to remove attributes that should not be searched. 
 
  $criteria=new CDbCriteria; 
 
  $criteria->with = array('author'); //添加了和 author 的渴求式加载 
 
  $criteria->compare('post_id',$this->post_id); 
  $criteria->compare('title',$this->title,true); 
  $criteria->compare('content',$this->content,true); 
  $criteria->compare('tags',$this->tags,true); 
  $criteria->compare('status',$this->status); 
  $criteria->compare('create_time',$this->create_time); 
  $criteria->compare('update_time',$this->update_time); 
  $criteria->compare('author_id',$this->author_id); 
 
  //这里添加了一个 compare, username 是 User 表的字段,$this->name 是我们添加的属性,true 为模糊搜索 
  $criteria->compare('username',$this->name,true); 
 
  return new CActiveDataProvider($this, array( 
    'criteria'=>$criteria, 
  )); 
} 

Copy after login


然后在 view 里面,就是 post 文件夹的 admin.php ,CGridView 改为下面代码:

<&#63;php $this->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', 
    /*下面就是添加的代码啊*/ 
    array( 
      'name'=>'作者名称', 
      'value'=>'$data->author->username', //定义展示的 value 值 
      'filter'=>CHtml::activeTextField($model,'name'), //添加搜索 filter 
    ), 
    array( 
      'class'=>'CButtonColumn', 
    ), 
  ), 
)); &#63;> 
Copy after login

你是不是发现现在有了搜索框但是不起作用呢?哈哈,所以我们说文章要坚持看到最后。我们要做的最后一步,就是在 rule 里面,把 name 属性加入到安全搜索字段中,要不然会被 Yii 认为是不安全字段而过滤掉的。看,就在下面函数的最后一行,safe 前面多了个 name ....

public function rules() 
{ 
  // NOTE: you should only define rules for those attributes that 
  // will receive user inputs. 
  return array( 
    array('title, content, status, author_id', 'required'), 
    array('status, create_time, update_time, author_id', 'numerical', 'integerOnly'=>true), 
    array('title', 'length', 'max'=>128), 
    array('tags', 'safe'), 
    // The following rule is used by search(). 
    // @todo Please remove those attributes that should not be searched. 
    array('post_id, title, content, tags, status, create_time, update_time, author_id, name', 'safe', 'on'=>'search'), 
  ); 
} 

Copy after login


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1049137.htmlTechArticlePHP的Yii框架的基本使用示例,yii框架示例 在 Yii 自动生成的代码里,我们总能在 admin 的界面看到 CGridView 的身影。这是一个很好用的展示数...
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles