Yii中CGridView关联表搜索排序方法实例详解
本篇章节讲解Yii中CGridView关联表搜索排序方法。分享给大家供大家参考。具体实现方法如下: 在Yii CGridView 关联表搜索排序实现方法有点复杂,今天看了一老外写的了篇游戏,下面我整理一下与各位朋友分享一下,相信会对大家Yii框架的学习有所帮助。 首先,检查你的blog demo里的protectedmodelsComment.php,确保Comment模型有一个search的方法,如果没有,就用gii生成一个,我下载到的blog demo里倒是没有。 然后,写代码的时间到了,我们从 CommentController 开始,我们给它加一个 actionList: 代码如下: unsetAttributes();
if(isset($_GET['Comment']))
$model->attributes=$_GET['Comment'];
$this->render('list',array( 着看起来没什么了不起的,跟你用gii生成的crud代码里的一样。现在让我来创建view,在 /protected/views/comment/ 目录下创建list.php然后粘贴以下代码 代码如下: breadcrumbs=array(
'Comments',
);
?>
Manage Comments<?php $this->widget('zii.widgets.grid.CGridView',array( Comment List 这是一个基本的 CGridView 只显示评论的‘content',‘status' and ‘author',和文章的标题。我们假设想要往这张list里添加一列文章的标题,我们只需要添加post.title 就行了: 代码如下: array(
'content',
'author',
),
现在如果你访问以下这个页面,发现文章的标题的确显示出来了 问题:如果你仔细瞅瞅这个页面你会发现你无法搜索文章标题,你也没办法按文章标题排序,这是因为 CGridView 在给定的 column name 里面发现了一个‘.',也就是 post.title 的点。如果有点号的话,它就不会生成搜索框。 解决方案:要想解决这个问题,我们得费点力气。首先我们得给Commen模型添加一个 getter 和一个 setter ,比如说这么写: 代码如下: _postTitle === null && $this->post !== null)
{
$this->_postTitle = $this->post->title;
}
return $this->_postTitle;
}
public function setPostTitle($value)
{
$this->_postTitle = $value;
}
接下来将这个属性添加到 rules 函数里: 代码如下: 128),
array('email','email'),
array('url','url')
array('content,postTitle,status,author','safe','on'=>'search'), 这还不够,最需要改动的是我们的 search 函数。首先我们要添一个 criteria: 代码如下: with = "post"; // 确保查询 post 表
$criteria->compare('t.content',$this->content,true); 然后我们添加排序: 代码如下: attributes = array(
'defaultOrder'=>'t.create_time DESC',
'content'=>array(
'asc'=>'t.content',
'desc'=>'t.content desc',
),
'status'=>array(
'asc'=>'t.status',
'desc'=>'t.status desc',
'author'=>array(
'asc'=>'t.author',
'desc'=>'t.author desc',
'postTitle'=>array(
'asc'=>'post.title',
'desc'=>'post.title desc',
);
你也许注意到了我在使用完整的 ‘tablename'.'columnname'语法,我这么做的原因是为了避免 mysql 抛出‘column is ambigious error'。 为了保证这一切正常运行,我们必须传递 CSort 实例和 CDbCriteria 实例给 CActiveDataProvider : 代码如下: $criteria,
'sort'=>$sort
));
return new CActiveDataProvider('Comment', 'sort'=>$sort )); 现在我们要做的就是修改我们的 view 以便它在 CGridView 显示想要显示的属性: 代码如下: array(
'content',
'postTitle',
刷新一下,应该可以了,效果如下图所示: 希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |