在Yii多模型表单中获取错误

时间:2012-01-19 19:47:03

标签: php yii undefined yii-cmodel

我是Yii框架的新手。我想要一个多模式表单,所以我只是通过this link并做了所有这样的事情。我有两个表,第一个是组,另一个是成员。

Group

 ID
 name

 Member

 id
 group_id
 firstname
 lastname

现在我已经为表和CRUD制作了模型。我对GroupController文件进行了更改

public function actionCreate()
  {
    $group = new Group;
    $member = new Member;
    if(isset($_POST['Group'],$_POST['Member'])) {
    //Populate input data to $group and $member
      $group->attributes = $_POST['Group'];
      $member->attributes = $_POST['Member'];

    //Validate both $group and $member
      $validate = $group->validate();
      $validate = $member->validate() && $valid;

      if($valid){
        $group->save(false);
        $member->save(false);
      }
    }
    $this->render('create',array(
      'group'=> '$group',
      'member'=> '$member',
    ));
    $model=new Group;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Group']))
    {
      $model->attributes=$_POST['Group'];
      if($model->save())
        $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('create',array(
      'model'=>$model,
    ));
  }

并在更改群组后>>查看>>像这样的create.php文件

<?php echo $this->renderPartial('_form', array('group'=>$group, 'member'=>$member)); ?>

_form文件就像这样

<div class="form">

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

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

  <?php echo $form->errorSummary($group,$member); ?>

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

  <div class="row">
    <?php echo $form->labelEx($member,'firstname'); ?>
    <?php echo $form->textField($member,'firstname',array('size'=>60,'maxlength'=>128)); ?>
    <?php echo $form->error($member,'firstname'); ?>
  </div>

  <div class="row buttons">
    <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
  </div>

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

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

但毕竟我收到这样的错误Undefined variable: group . 那么有人可以告诉我如何解决这个问题。我已经失去了一天。所以任何帮助和建议都会非常值得注意。

1 个答案:

答案 0 :(得分:2)

你在这里犯了多个错误 - &gt;

致电

 $this->render('create',array(
      'model'=>$model,
    ));

您没有传递您在组创建控制器中创建的$ group或$ member模型。将其更改为 -

 $this->render('create',array(
      'group'=>$group,
      'member'=>$member,
    ));

其次,没有名为$ valid的变量......更改此部分

$validate = $member->validate() && $valid;

  if($valid){

$validate = $member->validate() && $validate;

      if($validate){

现在事情应该可以正常工作