在帖子yii中添加评论

时间:2012-10-31 06:08:03

标签: yii

我想在我的博客网站上添加评论模块。我所做的是:

否1在博客帖子view.php中添加<div>以呈现tblcomments / _form

<?php 

        $model_comments = new TblComments;

   $this->renderPartial('/TblComments/_form',array(
            'comments'=>$model_comments,
        ));

 ?>

No 2:这是我的TblComments / _form.php

&LT;

div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'tbl-comments-form',
    'enableAjaxValidation'=>false,
)); ?>

    <p class="note">Fields with <span class="required">*</span> are required.</p>

    <?php echo $form->errorSummary($model_comments); ?>

    <div class="row">
        <?php // echo $form->labelEx($model,'user_id'); ?>
        <?php echo $form->hiddenField($model_comments,'user_id'); ?>
        <?php echo $form->error($model_comments,'user_id'); ?>
    </div>

    <div class="row">
        <?php // echo $form->labelEx($model,'post_id'); ?>
        <?php echo $form->hiddenField($model_comments,'post_id'); ?>
        <?php echo $form->error($model_comments,'post_id'); ?>
    </div>
    <div class="row">
        <?php echo $form->labelEx($model_comments,'comment_body'); ?>
        <?php echo $form->textArea($model_comments,'comment_body',array('rows'=>5,'cols'=>35)); ?>
        <?php echo $form->error($model_comments,'comment_body'); ?>
    </div>
    <div class="row buttons">
        <?php echo CHtml::submitButton($model_comments->isNewRecord ? 'Create' : 'Save'); ?>
    </div>

<?php $this->endWidget(); ?>

</div><!-- form -->

问题是:

Undefined variable: model_comments 

P.S:这个错误发生在TblComments / _form文件的行上:

<?php echo $form->errorSummary($model_comments); ?>

任何人都可以解释为什么这个未定义,因为我已经定义了它!

2 个答案:

答案 0 :(得分:2)

我只需添加

  $model_comments =  new TblComments();

在TblComments / _form.php

答案 1 :(得分:1)

这是一个小错误,当你这样做时:

$this->renderPartial('/TblComments/_form',array(
    'comments'=>$model_comments,
));
// or even if you are using render()

传递给模型实例的视图将其视为$comments而不是$model_comments,这意味着如果您这样做:

$this->render('someview', array('model_there'=>$model_here));

视图必须使用$model_there而不是$model_here。如the guide中所述:

  

render()方法将第二个数组参数提取到变量中。因此,在视图脚本中,我们可以访问局部变量$ var1和$ var2。


那说你应该将实例创建移动到控制器,然后将其传递给你的视图:

// controller action
public function actionActionname($id){
    $model_here = new TblComments;
    $postmodel = loadModel($id);
    // ...
    $this->render('view', array(
        'postmodel'=>$postmodel,
        'model_there'=>$model_here
    ));
}

// in view.php
$this->renderPartial('/TblComments/_form', array(
    'model_there'=>$model_there
);

// then in _form you use $model_there
<?php echo $form->errorSummary($model_there); ?>