如何在一个表单中验证不同的模型字段?Yii

时间:2014-03-21 06:47:46

标签: php validation yii validationrules

我有两个型号

1) TblRegistration :$ model as object

 -director
 -experience
 -language

2) TblLogin :$ model2作为对象

 -email
 -password

这两个字段都包含在TblRegistration / _form.php

通过defaut TblRegistration字段验证包含在rules()中。

视图/ tblRegistration / _form.php这个

<div class="row">
<?php echo $form->labelEx($model,'director'); ?>
<?php echo $form->textField($model,'director',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($model,'director'); ?>
</div>

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

<div class="row">
<?php echo $form->labelEx($model,'language'); ?>
<?php echo $form->textField($model,'language',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($model,'language'); ?>
</div>

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

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

模型/ TblRegistration.php

    public function rules()     {
     // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('director, experience, language', 'required'),
        array('experience', 'numerical', 'integerOnly'=>true),
        array('director, language', 'length', 'max'=>50),
        // The following rule is used by search().
        // @todo Please remove those attributes that should not be searched.
        array('reg_id, director, experience, language', 'safe', 'on'=>'search'),
    );
    }

我想将TblLogin字段包含在model / TblRegistraion规则中以进行验证。

1 个答案:

答案 0 :(得分:0)

您可以通过调用validate()方法手动验证模型:

if($modelA->validate() && $modelB->validate()) {
    // Call save method, fix foreign keys, etc
    $this->redirect(array('view'));
}

如果出现错误,页面将不会被重定向,因此您的表单将重新加载。 $form->error()将突出显示错误字段。此外,当errorSummary的第一个参数是包含模型的数组时,它会为您总结它们。