Yii中的评论系统

时间:2016-09-13 17:42:28

标签: yii

我尝试在这个示例http://yiiframework.ru/doc/blog/en/comment.create中创建Yii 1.1中的注释但是我在帖子页面上有404错误(应该在页面底部呈现内容和注释表单)。我认为我在PostController中的actionView中有错误,如示例代码中的

 $post=$this->loadModel();
    $comment=$this->newComment($post);

    $this->render('view',array(
        'model'=>$post,
        'comment'=>$comment,
    ));

在我的控制器中,初始代码为$this->render('view',array('model'=>$this->loadModel($id),

我在gii中创建了评论模型,并在crud中创建了评论。

public function actionView($id)
    {
            $post=$this->loadModel();
            $comment=$this->newComment($post);

            $this->render('view',array(
            'model'=>$post,
            'comment'=>$comment,
            //$this->loadModel($id),                

        ));
    }

protected function newComment($post)
{
    $comment=new Comment;
    if(isset($_POST['Comment']))
    {
        $comment->attributes=$_POST['Comment'];
        if($post->addComment($comment))
        {
            if($comment->status==Comment::STATUS_PENDING)
                Yii::app()->user->setFlash('commentSubmitted','Thank you for your comment. Your comment will be posted once it is approved.');
            $this->refresh();
        }
    }
    return $comment;
}

在Post模型中:

public function addComment($comment)
    {
        if(Yii::app()->params['commentNeedApproval'])
            $comment->status=Comment::STATUS_PENDING;
        else
            $comment->status=Comment::STATUS_APPROVED;
        $comment->post_id=$this->id;
        return $comment->save();
    }

在protected / views / post / view.php

<div id="comments">
    <?php if($model->commentCount>=1): ?>
        <h3>
            <?php echo $model->commentCount . 'comment(s)'; ?>
        </h3>

        <?php $this->renderPartial('_comments',array(
            'post'=>$model,
            'comments'=>$model->comments,
        )); ?>
    <?php endif; ?>
</div>

1 个答案:

答案 0 :(得分:0)

在actionView方法中,您没有将$ id传递给loadModel()。它应该是这样的。

public function actionView($id)
    {
            $post=$this->loadModel($id);
            $comment=$this->newComment($post);

            $this->render('view',array(
            'model'=>$post,
            'comment'=>$comment,
            //$this->loadModel($id),                

        ));
    }

否则,loadModel方法将抛出404错误,因为它无法找到要加载的内容。

相关问题