Bookmark and Share

Lee's 程序人生

HTML CSS Javascript XML AJAX ATLAS C# C++ 数据结构 软件工程 设计模式 asp.net Java 数字图象处理 Sql 数据库
  博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

YiiFrameworkBlog开发向导:添加和显示评论

Posted on 2010-02-24 21:47  analyzer  阅读(316)  评论(0)    收藏  举报

本节中我们实现了评论的添加和显示

显示评论

我们采用文章的显示页面来添加和显示评论。在显示完正文之后我们显示评论的列表和添加评论的提交表单。

为了在文章显示页面显示评论列表,我们如下修改PostController的actionShow()方法。

 
  1. public function actionShow()
  2. {
  3.     $post=$this->loadPost();
  4.     $this->render('show',array(
  5.         'post'=>$post,
  6.         'comments'=>$post->comments,
  7.     ));
  8. }

 

注意表达式 $post->comments 是有效的,因为我们在Post(文章)类中声明了和comments(评论)的相关关系。该表达式会引发一个潜在的数据库连接查询来获取当前文章相关的评论。This feature is known as lazy relational query.

我们还需要修改显示的视图文件,在显示文章后添加评论的显示。在此不再做详细介绍。

添加评论

为了处理评论的添加。我们先如下修改PostController的actionShow()方法

 
  1. public function actionShow()
  2. {
  3.     $post=$this->loadPost();
  4.     $comment=$this->newComment($post);
  5.     $this->render('show',array(
  6.         'post'=>$post,
  7.         'comments'=>$post->comments,
  8.         'newComment'=>$comment,
  9.     ));
  10. }
  11.  
  12. protected function newComment($post)
  13. {
  14.     $comment=new Comment;
  15.     if(isset($_POST['Comment']))
  16.     {
  17.         $comment->attributes=$_POST['Comment'];
  18.         $comment->postId=$post->id;
  19.         $comment->status=Comment::STATUS_PENDING;
  20.  
  21.         if(isset($_POST['previewComment']))
  22.             $comment->validate('insert');
  23.         else if(isset($_POST['submitComment']) && $comment->save())
  24.         {
  25.             Yii::app()->user->setFlash('commentSubmitted','Thank you...');
  26.             $this->refresh();
  27.         }
  28.     }
  29.     return $comment;
  30. }


在上面的代码中,我们在显示视图前调用了newComment()方法。在newComment()方法中,我们生成了Comment实例,并且检查评论的表单是否提交。表单的提交可能是点击了提交按钮或者预览按钮。对于前者我们保存信息并用flash message进行了提示。flash message 中的信息仅提示一次,当我们再次刷新页面的时候将不会出现。

我们也需要修改视图文件,来增加添加评论的表单

 
  1. ......
  2. <?php $this->renderPartial('/comment/_form',array(
  3.     'comment'=>$newComment,
  4.     'update'=>false,
  5. )); ?>

在这里我们通过调用视图文件blog/protected/views/comment/_form.php实现了添加评论的表单。actionShow传递的变量$newComment,保存了用户要输入评论内容。变量update声明为false,是为了指出此处是新建评论。

为了支持评论的预览,我们需要在添加评论的表单中增加预览按钮。当预览按钮被点击,在底部显示评论的预览。下面是修改后的评论表单

 
  1. ...comment form with preview button...
  2.  
  3. <?php if(isset($_POST['previewComment']) && !$comment->hasErrors()): ?>
  4. <h3>Preview</h3>
  5. <div class="comment">
  6.   <div class="author"><?php echo $comment->authorLink; ?> says:</div>
  7.   <div class="time"><?php echo date('F j, Y \a\t h:i a',$comment->createTime); ?></div>
  8.   <div class="content"><?php echo $comment->contentDisplay; ?></div>
  9. </div><!-- post preview -->
  10. <?php endif; ?>

注意: 上面的代码只是预览部分,并没有包括预览按钮,请参照文章的预览按钮添加