Basic use example of the Yii Framework of PHP, yii Framework example _ PHP Tutorial

Source: Internet
Author: User
The basic usage example of the Yii Framework of PHP, and the yii Framework example. The basic usage example of the Yii Framework in PHP. the yii Framework example shows CGridView in the automatically generated Yii code on the admin interface. This is a basic example of Yii Framework for displaying PHP Data. yii Framework example

In the automatically generated Yii code, we can always see the CGridView figure on the admin interface. This is a very useful table control for displaying data, which can significantly speed up development. Next let's explore the basic use of CGridView:

For simplicity, we use the blog example in Yii demo to modify the code. First, here are some modified Mysql statements:

Drop table if exists 'tbl _ user'; create table tbl_user ('User _ id' integer not null AUTO_INCREMENT comment 'primary key', 'username' VARCHAR (128) not null comment 'username', 'nickname' VARCHAR (128) not null comment' nickname ', 'password' VARCHAR (128) not null comment 'password ', 'email 'varchar (128) not null comment' mailbox ', 'Is _ delete' tinyint not null default 0 comment' delete flag', unique key ('Username '), primary key ('User _ id') ENGINE = InnoDB default charset = utf8 comment = 'User table'; drop table if exists 'tbl _ post '; create table tbl_post ('post _ id' integer not null AUTO_INCREMENT comment 'primary key', 'title' VARCHAR (128) not null comment 'title ', 'content' text not null comment' article content', 'tags' TEXT comment' tags', 'status' integer not null comment' status, 0 = Draft, 1 = approved, -1 = rejected Review, 2 = release', 'create _ time' INTEGER comment 'creation time', 'update _ time' INTEGER comment' update time ', 'author _ id' integer not null comment' author ', 'Is _ delete' tinyint not null default 0 comment' delete flag', 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 = 'Log table ';

Two tables store the author information and one storage log. the log has a foreign key associated with the user. The is_delete field in the two tables indicates whether the record is deleted, 0 indicates not deleted, and 1 indicates deleted. Let's take a look at the relation method of the Post class generated using 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'),   ); } 

The author foreign key exists as the BELONGS_TO relationship, which meets our expectation.
Let's take a look at the CGridView code in admin. php in the automatically generated Post:

<?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',     ),   ), )); ?> 

Look! Although we did not write anything, this is the most basic use of this control. DataProvider is the data provided by the search function in the model, filter... currently, this function is unavailable. columns controls each column displayed. the CButtonColumn of the last item shows us three buttons: viewing updates and deleting.
Next we will make a little transformation.

Use CGridView to show the real data format:
Most of the time, what is in the database is not suitable for direct display to the user, we need to make some processing before it is suitable for reading. However, without modification, the CGridView will only present the database value intact, so we should modify the corresponding field. For example, the is_delete field stores 0 and 1 in the database, but reading here is not very good. we should change it to 1 to display 'yes' and 0 to show 'no '. Let's take a look at the following code. We use an array. The two keys are name and value, respectively. The field corresponding to name needs to be filled in with the model, and value is the data you want to display, you can write a php statement as the executable code. Do you think we can do a lot for this value? Some may ask, if the code I want to execute is long, do they all write in the value ?... I said, classmate, won't you write a function elsewhere and then call it here ??

<? 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? "Yes": "No" '// value can execute php statements.) array ('class' => 'cbuttoncolumn',),);?>

In addition, there are some common options that can be filled in the array. The following is a common usage (other part of the code is omitted ):

Array ('name' => 'is _ delete', 'value' => 'is _ delete? "Yes": "No" '// value indicates that php statements can be executed. 'filter' => array (0 => 'no', 1 =>' Yes '), // customize the search filtering method. here, the drop-down menu 'htmlopexception' => array ('class' => 'Delete') is set to yes or no '), // html options can be defined. here, a class with a delete is defined ),

If we use name above, it is the original field in the model. if we want to display our new content, use the header:

Array ('header' => 'note', 'value' => 'Display your data '),

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

<? Php $ this-> widget ('zii. widgets. grid. CGridView ', array ('id' => 'Post-grid', 'dataprovider' => $ model-> search (), 'filter' => $ model, 'columns '=> array ('selectablerows' => 2, // you can select multiple columns. if you change the value to 0, tables cannot be modified, 1: Select 'class' => 'ccheckboxcolumn', // check box 'headerhtmloptions '=> array ('width' => '18px '), // the header's html options 'checkboxhtmloptions '=> array ('name' => 'myname', 'class' => 'myclass'), // the check box's html options ), 'Post _ id', 'Ti Tle ', 'content', 'tags', 'status', 'create _ time', 'update _ time', 'author _ id', 'is _ delete ', array ('name' => 'is _ delete', 'value' => 'is _ delete? "Yes": "No" ', // value can execute php statements. 'filter' => array (0 => 'no ', 1 => 'Yes'), // You can customize the search filtering method, here is the drop-down menu 'htmloptions '=> array ('class' => 'Delete') for "yes" and "no". // you can define html options, here is the definition of a class with a delete), array ('class' => 'cbuttoncolumn ',),),));

Modify ButtonColumn:
Have you noticed the last three icons of each item in the list? If this is not necessary, delete it directly. what if there are only a few of them? You can add a template parameter:

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

You can also customize the buttons:

Array ('class' => 'buttoncolumn', 'template' => "{view} {update} {print }", 'buttons' => array ('print' => array ('label' => 'Print', 'URL' => 'yii: app () -> controller-> createUrl ("print", array ("id" => $ data-> post_id ))', 'options' => array ("target" => "_ blank "),),),),

Javascript triggered during refresh:
If you want to trigger some Javascript after each search, Yii also provides this option. you only need to write a function and set afterAjaxUpdate. remember that this is only called after the ajax request is complete, if you want to call the function at the beginning of page loading, you need to add the Javascript code 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, // Here, the javascript called after ajax is here .... 'columns '=> array ('selectablerows' => 2, // you can select multiple columns. if you change the value to 0, tables cannot be modified, 1: Select 'class' => 'ccheckboxcolumn', // check box 'headerhtmloptions '=> array ('width' => '18px '), 'checkboxhtmloptions '=> array ('name' => 'myname', 'class' => 'myclass '),),....

Search related fields in the joined table:
First, we will only talk about "one-to-many" association search here. first, do not forget our database. if you forget it, please stamp it here: here, we can see that there is a foreign key associated with the tbl_user table in tbl_post to find information about the author. After the database is created, check the POST Model of the Yii code we generated. the realtion is as follows (ignore 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'),   ); } 

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.
After talking about this, what are our requirements ?....

The product manager pushed the glasses: "We need to add a function on the log background management interface. you can search for the corresponding articles by the author name. This is urgent and will be completed tonight. "

Don't you just change your needs. Ignore the progress requirement. let's look at what to do.
In fact, it is very simple, not to add a column of author names in the POST admin interface, and then you can find the corresponding log through the fuzzy search of the author name? Look at the code. isn't it easy to search by author id? But it's really unfriendly... isn't it easy to show the author's name? Add a header and set the value to $ data-> author-> username. The problem is that the header can only be displayed, but cannot be searched.
Not multiple searches? Come on, let me tell you how to do it.

First, we enter the POST model and add an attribute at the beginning:

Class Post extends CActiveRecord {public $ name; // add a public attribute to indicate the author's name and then modify the search code in the Model. the changes have been added with comments: public function search () {// @ todo Please modify the following code to remove attributes that shocould not be searched. $ criteria = new CDbCriteria; $ criteria-> with = array ('author '); // added and author eager loading $ 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); // here a compare is added, username is the field of the User table, $ this-> name is the attribute we added, true: Fuzzy search $ criteria-> compare ('username', $ this-> name, true); return new CActiveDataProvider ($ this, array ('criteria '=> $ criteria ,));}


In the view, the admin. php file in the post folder is changed to the following code:

<? 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 the added code */array ('name' => 'author name ', 'value' => '$ data-> author-> username', // define the value 'filter' => CHtml: activeTextField ($ model, 'name'), // add search filter), array ('C Lass '=> 'cbuttoncolumn',);?>

Did you find that the search box does not work now? Haha, so we say that we should stick to seeing the end of the article. The last step is to add the name attribute to the security search field in the rule. Otherwise, the attribute will be filtered out by Yii as an insecure field. Look, in the last row of the following function, there is a name in front of safe ....

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'),   ); } 


In the Yii automatically generated code, we can always see the CGridView figure on the admin interface. This is a good display number...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.