Home > Article > Backend Development > Detailed explanation of examples of search and sorting methods for CGridView association tables in Yii, yiicgridview_PHP tutorial
The example in this article describes the search and sorting method of CGridView association table in Yii. Share it with everyone for your reference. The specific implementation method is as follows:
The implementation method of searching and sorting the association table in Yii CGridView is a bit complicated. Today I read a game written by a foreigner. Now I will sort it out and share it with my friends. I believe it will be helpful for everyone to learn the Yii framework.
First of all, check protectedmodelsComment.php in your blog demo to make sure the Comment model has a search method. If not, use gii to generate one. There is no search method in the blog demo I downloaded.
Then, it’s time to write code. We start with CommentController and we add an actionList to it:
It doesn’t look like much, it’s the same as the crud code you generated with gii. Now let me create the view, create list.php in the /protected/views/comment/ directory and paste the following code
Comment List
This is a basic CGridView that only displays the comment’s ‘content’, ‘status’ and ‘author’, and the post’s title. Suppose we want to add a column of article titles to this list, we only need to add post.title:
Now if you visit the following page, you will find that the title of the article is indeed displayed
Question:
If you take a closer look at this page, you will find that you cannot search for article titles, and you cannot sort by article titles. This is because CGridView found a '.' in the given column name, which is post. The point of title. If there is a dot, it will not generate a search box.
Solution:
To solve this problem, we have to work hard. First we have to add a getter and a setter to the Commen model, for example:
Next add this attribute to the rules function:
This is not enough, what needs to be changed most is our search function. First we need to add a criteria:
Then we add sorting:
You may have noticed that I am using the full 'tablename'.'columnname' syntax. The reason I do this is to avoid mysql throwing a 'column is ambigious error'.
In order for this to work properly, we must pass a CSort instance and a CDbCriteria instance to the CActiveDataProvider:
return new CActiveDataProvider('Comment', array(
'criteria'=>$criteria,
'sort'=>$sort
));
Now all we have to do is modify our view so that it displays the properties we want to display in the CGridView:
Refresh it and it should be fine. The effect is as shown below:
I hope this article will be helpful to everyone’s PHP program design based on the Yii framework.