0

我正在尝试在我的博客网站中添加评论模块。我所做的是:

否 1<div>在博客文章 view.php 中添加一个以呈现 tblcomments/_form

<?php 

        $model_comments = new TblComments;

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

 ?>

第 2 号:这是我的 TblComments/_form.php

<

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 

PS:这个错误发生在 TblComments/_form 文件上:

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

谁能解释我为什么这个未定义,因为我已经定义了它!

4

2 回答 2

2

我只是添加

  $model_comments =  new TblComments();

在 TblComments/_form.php

于 2012-10-31T06:39:34.697 回答
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。如指南中所述

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); ?>
于 2012-10-31T08:24:46.263 回答