PHP's YII framework Basic use Example _php instance

Source: Internet
Author: User
Tags yii

In Yii automatically generated code, we can always see Cgridview in the admin interface. This is a very useful display data table control, with good can obviously speed up the development progress. Now let's explore the basic use of Cgridview:

For simplicity, our code is modified with a blog example from the Yii demo. First, this is the modified part of the MYSQL statement:

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 CO Mment ' 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 comme NT ' title ', ' content ' text not null comment ' article contents ', ' tags ' text comment ' tags ', ' status ' INTEGER not null comment ' state, 0 = Draft, 1 = Audit Pass,-1 = audit does not pass, 2 = Publish ', ' 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 the DELETE CASCADE on UPDATE RESTRICT, primary 

 Key (' post_id ')) engine=innodb DEFAULT Charset=utf8 comment= ' Log table ';

Two tables one stores the author information A storage log in which a foreign key is associated with the user. The Is_delete field in the two table is to flag whether the record is deleted, 0 is not deleted, and 1 is deleted. Let's take a look at the relation method for the Post class that is generated in GII:

/** 
 * @return Array relational rules. 
 */Public 
function relations () 
{ 
  //note:you could need to adjust the relation name and the related 
  //clas s 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 ') 
  ; 
} 

One of the author foreign keys as a belongs_to relationship exists, in line with our expectations.
Having said so much, look at the code in admin.php in the automatically generated Post: Cgridview.

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

See! 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 model, filter ... Temporarily do not see the role here, columns control the display of each column, one of the last Cbuttoncolumn showed us three buttons, respectively, to view the update and delete.
And then we change it a little bit.

The

displays the data form we really want with Cgridview:
    many times, the things in the database are not suitable for direct display to the user, we need to do some processing before it is suitable for reading. But here, without modification, Cgridview will only render the value of the database intact, so we should modify it in the corresponding field. For example, the Is_delete field, the database is stored in 0 and 1, but reading here is not very good, we should be changed to 1 show ' yes ', 0 show ' no '. Look at the following code, we used an array, two keys are name and value,name corresponding to fill in the model owned fields, and value is the data you want to display, here can be written as a PHP statement, as executable code. See here, do you think we can do a lot of things about this value? Some students may ask, if I want to execute the code is very long, it is written in value? I said classmate, you will not write a function somewhere else 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 is able to execute the PHP statement of the OH 
    ) 
    Array ( 
      ' class ' => ' Cbuttoncolumn ',),)) 
;?> 

In addition, there are some commonly used options, can be filled in the array, the following is a more common way to use (other parts of the code omitted):

Array ( 
  ' name ' => ' is_delete ', ' 
  value ' => ' Is_delete? ') Yes ":" "no" '//value is the 
  => array (0=> ' no ',1=> ') that can execute PHP statements,//define your own search filtering mode, here for Yes and no drop-down menu 
  ' Htmlop tions ' =>array (' class ' => ' delete '),//Can define HTML options, here is a class with a delete defined. 
 

The above we use name words that is the model of the original field, if we want to show their definition of new content, with header:

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

Add Ccheckboxcolumn:
Sometimes we may need a check box to select each row, at which point we can add a column with the Ccheckboxcolumn class:

<?php $this->widget (' Zii.widgets.grid.CGridView ', array (' ID ' => ' post-grid ', ' Dataprovider ' => $model Search (), ' Filter ' => $model, ' columns ' =>array (Array (' Selectablerows ' => 2,//Allow multiple selections, change to 0 o'clock means not allowed Modified, 1 words for the single ' class ' => ' Ccheckboxcolumn ',//checkbox ' Headerhtmloptions ' => array (' width ' => ' 18px '),//head H 
    tml option ' checkboxhtmloptions ' => Array (' name ' => ' myname ', ' class ' => ' MyClass '),//check box HTML options), ' post_id ', ' title ', ' content ', ' tags ', ' status ', ' Create_time ', ' update_time ', ' author_ Id ', ' is_delete ', Array (' name ' => ' is_delete ', ' value ' => ' Is_delete?) Yes ":" No "',//value is able to execute the PHP statement of the OH ' filter ' => array (0=> ' no ',1=> ' is '),//define your own search filtering mode, here for Yes and no dropdown menu ' HT Mloptions ' =>array (' class ' => ' delete '),//Can define HTML options, here is a class with a delete defined, array (' class ' => ' CBu  

 Ttoncolumn ',),));

Modify ButtonColumn:
Notice the last three small icons for each item in the list? If you do not need it, of course, it is deleted directly, if only a few of them? You can add a template parameter:

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

You can also customize the button:

Array ( 
  ' class ' => ' ButtonColumn ', ' 
  template ' => ' {view} {update} {print} '), 
  ' buttons ' =>array ( 
      ' print ' =>array ( 
          ' label ' => ' printing ', 
          ' url ' => ' Yii::app ()->controller->createurl ("The Print ", Array (" id "=> $data->post_id)) ', ' 
          options ' =>array (" target "=>" _blank "),),) 
    , 

Javascript triggers when refreshing:
if you want to trigger some Javascript after each search, Yii also provides this option, you just write a function and then set the Afterajaxupdate, remember this is only called after the AJAX request is completed, if you want to finish loading the page at the beginning The call of achievement requires additional Javascript 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,//Look here, Ajax calls after JavaScript here ... 
  ' Columns ' =>array ( 
    array ( 
      ' Selectablerows ' => 2,//Allow multiple selections, change to 0 o'clock means not allowed to modify, 1 words for radio 
      ' class ' => ') Ccheckboxcolumn ',//check box 
      ' headerhtmloptions ' => array (' width ' => ' 18px '), 
      ' checkboxhtmloptions ' => Array (' name ' => ' myname ', ' class ' => ' MyClass '), 
    .... 

To add a search for related fields in the associated table:
first of all, we are here to talk about "One-to-many" Association search, first of all, do not forget our database, forget the classmate please stamp here: here, you can see in the tbl_post is a foreign key association to the Tbl_user table, to find information about the author. After building the database, look at the POST model of the YII code we generated, which is realtion as follows (ignoring comment):

/** 
 * @return Array relational rules. 
 */Public 
function relations () 
{ 
  //note:you could need to adjust the relation name and the related 
  //clas s 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 this is a belongs_to relationship.
Speaking so much, what is our demand? ....

The product manager pushed the glasses: "We're going to add a feature to the admin interface in the log, and we can search through the author's name for the appropriate article." This is more urgent and will be finished tonight. “

Calm and calm, not just change the demand. Ignoring progress requirements, let's look at what we're going to do.
In fact, it is very simple, not just add a list of author names in the admin interface of POST, and then you can find the corresponding log through the fuzzy search of the author's name? Look at the code, if the search through the author ID is not easy? But it's really not very friendly ... Isn't it easy to show the author's name? Add a header and then value is $data->author->username, the problem is this can only show, not search ... Ah, good distress.
Calm and calm, not just multiple search? Come on, let me tell you what to do.

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

Class Post extends Cactiverecord {public $name;//Add a public attribute, on behalf of the author name and then change the Model search code, the changes have been added to the comments: PU 
 
  Blic function Search () {//@todo please modify the following code to remove attributes that should is not searched. 
 
  $criteria =new Cdbcriteria; $criteria->with = Array (' author '); 
  Added and author-hungry 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); A compare is added here, username is the field of the User table, $this->name is the attribute we added, true is the fuzzy search $criteria->compare (' username ', $this-> 
 
  Name,true); return new Cactivedataprovider ($this, Array (' CRIteria ' => $criteria,)); 

 }


Then in the view, the Post folder is admin.php, Cgridview 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 ' 
    ,/* The following is the added code AH */ 
    Array (' name ' 
      => ' author name ', ' 
      value ' => ' $data->author->username ',//definition of the display value Value 
      ' filter ' =>chtml::activetextfield ($model, ' name '),//Add search filter 
    ), 
    Array ( 
      ' class ' => ' Cbuttoncolumn ',),)) 
;?> 

Did you find that you have a search box but it doesn't work? Haha, so we say the article should insist on seeing the last. The final step is to add the name attribute to the Safe search field in rule, or it will be filtered out by Yii as an unsafe field. Look, in the last line of the function below, safe is preceded by a name ....

Public function rules () 
{ 
  //note:you should only define the rules for those attributes that 
  //would receive user Inputs. 
  Return 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 is searched. 
    Array (' post_id, title, content, tags, status, Create_time, Update_time, author_id, name ', ' safe ', ' on ' => ' search '), c12/>); 
} 


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.