In the YII auto-generated code, we can always see the cgridview in the admin interface. This is a very useful form of presentation data control, with the good can significantly accelerate development progress. Let's explore the basic use of Cgridview:
For simplicity, our code uses the blog example from the Yii demo to make changes. 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 (+) not null comme NT ' username ', ' nickname ' varchar (+) NOT null comment ' nickname ', ' password ' varchar ' NOT null comment ' password ', ' email ' varc HAR (+) NOT null comment ' mailbox ', ' is_delete ' tinyint not null default 0 comment ' Delete flag ', unique key (' username '), prima Ry 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 (+) ' NOT NULL comment ' title ', ' content ' text not null comment ' article content ', ' tags ' text comment ' tag ', ' status ' INTEGER not null comment ' state, 0 = draft , 1 = Audit passed, 1 = Audit not passed, 2 = Publish ', ' create_time ' integer comment ' Create Time ', ' update_time ' integer comment ' update time ', ' author_id ' INTEGER not null comment ' author ', ' is_delete ' tinyint not null default 0 comment ' Remove flag ', CONSTRAINT ' Post_ibfk_1 ' Forei GN KEY (author_id) REFERENCES tbl_user (' user_id ') on the DELETE CASCADE on UPDATE RESTRICT, primary key (' post_id ')) engine=in Nodb DEFAULT charset=utf8 comment= ' Log table ';
Two Tables one store author information a store log, where the log has a foreign key associated to the user. The Is_delete field in two tables is a flag that the record is deleted, 0 is not deleted, and 1 is deleted. Let's take a look at the relation method of the Post class generated with the GII:
/** * @return Array relational rules. */Public Function relations () { //note:you could need to adjust the relation name and the related//class name F Or 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 as a belongs_to relationship exists, in line with our expectations.
Having said so much, take a look at the code of admin.php Cgridview in the auto-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 ', ),
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 inside the model, filter ... Temporarily do not see the role here, columns control the display of each column, where the last item of the cbuttoncolumn showed us three buttons, respectively, to view the update and delete.
Next we're going to change a little bit.
Use Cgridview to show the form of data we really want:
Most of the time, the database is not suitable for direct display to the user to see, we need to do some processing before it is suitable for reading. But without modification here, Cgridview will only render the values of the database intact, so we should modify them in the corresponding fields. such as the Is_delete field, the database is stored in 0 and 1, but reading here is not very good, we should change 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 show, here can be written as a PHP statement, as can be executed code. See here, do you think we can do a lot of things for this value? Some students may ask, if I want to execute the code is very long, is it written in value? I said classmate, you do not write a function in other places 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 a PHP statement can execute the OH ) Array ( ' class ' = ' Cbuttoncolumn ', ),
In addition, there are some common options, can be filled in the array, the following is a more common use (other parts of the code omitted):
Array ( ' name ' = ' is_delete ', ' value ' = ' is_delete? ') is ":" "no" '//value is a PHP statement can execute the OH ' filter ' = = Array (0=> ' no ',1=> ' is '),//define the way of search filtering, here is yes and no drop-down menu
We use the name above, which is the original field in the model, if we want to show our own definition of new content, with the header:
Array ( ' header ' = ' Notes ',
Add Ccheckboxcolumn:
Sometimes we'll need a check box to make a selection for each row, and then 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 (' Sele Ctablerows ' + 2,//Allow multiple selection, change to 0 o'clock for no modification, 1 for single-select ' Class ' = ' ccheckboxcolumn ',//check box ' headerhtmloptions ' =& Gt Array (' width ' = ' 18px '),//Header HTML option ' checkboxhtmloptions ' = = Array (' name ' = ' myname ', ' class ' = ' MyClass ') '),//check box HTML option), ' post_id ', ' title ', ' content ', ' tags ', ' status ', ' Create_time ', ' upd ' Ate_time ', ' author_id ', ' Is_delete ', Array (' name ' = ' is_delete ', ' value ' = ' is_delete? ') is ":" No "',//value is able to execute the PHP statement of the OH ' filter ' = + Array (0=> ' no ',1=> ' is '),//define the way the search is filtered, here is yes and no drop-down menu ' HTML Options ' =>array (' class ' = ' delete '),//Can define HTML options, here is a class with a delete defined, and array (' class ' = ' = ' Cbuttonc Olumn ',),),));
Modify ButtonColumn:
Notice the last three small icons for each item in the list? If you do not need to, 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 buttons:
Array ( ' class ' = ' ButtonColumn ', ' template ' = ' {view} {update} {print} ', ' buttons ' =>array ( ' print ' =>array ( ' label ' = ' printing ', ' url ' = ' Yii::app ()->controller->createurl (" Array ("id" = $data->post_id)) ', ' Options ' =>array ("target" = "_blank"),),
Trigger Javascript when refreshing:
If you want to trigger some Javascript after each search, Yii also provides this option, just write a function and set afterajaxupdate, and remember that this is only called after the AJAX request is complete, if you want the page Javascript that needs to be added to the page at the beginning of the load completion
$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,//See here, the JavaScript that is called after Ajax is here .... ' Columns ' =>array ( array ( ' selectablerows ' = + 2,//Allow multiple selection, change to 0 o'clock for no modification, 1 for Radio ' class ' = ') Ccheckboxcolumn ',//check box ' headerhtmloptions ' = = Array (' width ' = ' 18px '), ' checkboxhtmloptions ' = Array (' name ' = ' myname ', ' class ' = ' MyClass '),
To add a search for related fields of the associated table:
First of all, we are here to talk about "one-to-many" relevance search, first of all, do not forget our database, forget the classmate please poke here: here, you can see that in tbl_post there is a foreign key associated to the Tbl_user table, to find information about the author. After the database has been built, look at the POST model of the YII code we generated, with the following realtion (ignoring comment):
/** * @return Array relational rules. */Public Function relations () { //note:you could need to adjust the relation name and the related//class name F Or 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.
Having said so much, what exactly is our demand? ....
The product manager pushed the glasses: "We want to add a function to the admin interface of the log, which can be searched by the author's name." This is more urgent, it's going to be finished tonight. “
Calm and calm, not just change demand. Ignoring the progress requirements, let's look at what we are 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 by the fuzzy search of the author's name. Look at the code, if the author ID to search is not easy? But this is really not very friendly ... Wouldn't it be easy to show the author's name? Add a header and then value is $data->author->username, the problem is that it can only be displayed, not searchable ... Ah, good distress.
Calm and calm, not just multiple searches? Come on, let me tell you what to do.
First, we enter the POST model, where we add an attribute at the beginning:
Class Post extends Cactiverecord {public $name;//Add a public property that represents the author name and then change the code of search in Model, the changes have been annotated: public F Unction Search () {//@todo modify the following code to remove attributes, that should not be searched. $criteria =new Cdbcriteria; $criteria->with = Array (' author '); Added and author The craving load $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 for fuzzy search $criteria->compare (' username ', $this- Name,true); return new Cactivedataprovider ($this, Array (' criteria ' = $criteria,)); }
Then in view, is the Post folder 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 ',/ * Below is the code added. */ Array ( ' name ' = ' author ', ' value ' = ' $data->author->username ',//define value displayed as ' Filter ' =>chtml::activetextfield ($model, ' name '),//Add search filter ), Array ( ' class ' = ' Cbuttoncolumn ', ),
Did you find that you now have a search box but it doesn't work? Haha, so we say the article to insist on seeing the last. The last step we have to make is to add the name attribute to the SafeSearch field in rule, otherwise it will be filtered out by Yii as an unsafe field. Look, just in the last line of the function below, safe has a name in front of it ....
Public Function Rules () { //note:you should-define rules for those attributes that //would receive user INP UTS. 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, should not being searched. Array (' post_id, title, content, tags, status, Create_time, Update_time, author_id, name ', ' safe ', ' on ' = ' search '),