本节中我们实现了评论的添加和显示
显示评论
我们采用文章的显示页面来添加和显示评论。在显示完正文之后我们显示评论的列表和添加评论的提交表单。
为了在文章显示页面显示评论列表,我们如下修改PostController的actionShow()方法。
?
- public?function?actionShow()
-
{
- ????$post=$this->loadPost();
- ????$this->render('show',array(
- ????????'post'=>$post,
- ????????'comments'=>$post->comments,
- ????));
- }
?
注意表达式 $post->comments 是有效的,因为我们在Post(文章)类中声明了和comments(评论)的相关关系。该表达式会引发一个潜在的数据库连接查询来获取当前文章相关的评论。This feature is known as lazy relational query.
我们还需要修改显示的视图文件,在显示文章后添加评论的显示。在此不再做详细介绍。
添加评论
为了处理评论的添加。我们先如下修改PostController的actionShow()方法
?
- public?function?actionShow()
-
{
- ????$post=$this->loadPost();
- ????$comment=$this->newComment($post);
- ????$this->render('show',array(
- ????????'post'=>$post,
- ????????'comments'=>$post->comments,
- ????????'newComment'=>$comment,
- ????));
-
}
- ?
- protected?function?newComment($post)
- {
- ????$comment=new?Comment;
- ????if(isset($_POST['Comment']))
-
????{
- ????????$comment->attributes=$_POST['Comment'];
- ????????$comment->postId=$post->id;
- ????????$comment->status=Comment::STATUS_PENDING;
-
?
- ????????if(isset($_POST['previewComment']))
- ????????????$comment->validate('insert');
- ????????else?if(isset($_POST['submitComment'])?&&?$comment->save())
- ????????{
- ????????????Yii::app()->user->setFlash('commentSubmitted','Thank?you...');
- ????????????$this->refresh();
- ????????}
-
????}
- ????return?$comment;
- }
在上面的代码中,我们在显示视图前调用了newComment()方法。在newComment()方法中,我们生成了Comment实例,并且检查评论的表单是否提交。表单的提交可能是点击了提交按钮或者预览按钮。对于前者我们保存信息并用flash message进行了提示。flash message 中的信息仅提示一次,当我们再次刷新页面的时候将不会出现。
我们也需要修改视图文件,来增加添加评论的表单
?
- ......
- <?php?$this->renderPartial('/comment/_form',array(
- ????'comment'=>$newComment,
- ????'update'=>false,
- ));??>
在这里我们通过调用视图文件blog/protected/views/comment/_form.php实现了添加评论的表单。actionShow传递的变量$newComment,保存了用户要输入评论内容。变量update声明为false,是为了指出此处是新建评论。
为了支持评论的预览,我们需要在添加评论的表单中增加预览按钮。当预览按钮被点击,在底部显示评论的预览。下面是修改后的评论表单
?
- ...comment?form?with?preview?button...
-
?
- <?php?if(isset($_POST['previewComment'])?&&?!$comment->hasErrors()):??>
- <h3>Preview</h3>
- <div?class="comment">
- ??<div?class="author"><?php?echo?$comment->authorLink;??>?says:</div>
- ??<div?class="time"><?php?echo?date('F?j,?Y?at?h:i?a',$comment->createTime);??></div>
- ??<div?class="content"><?php?echo?$comment->contentDisplay;??></div>
- </div><!--?post?preview?-->
- <?php?endif;??>
注意: 上面的代码只是预览部分,并没有包括预览按钮,请参照文章的预览按钮添加