yii中验证规则的场景

时间:2013-07-02 07:44:28

标签: php validation yii scenarios yii-validation

我在徘徊是否有机会使用规则方案,

在我的模型中我有

public function rules()
{
    return array(
        array('delivery, firstNameBilling, lastNameBilling, addressBilling, cityBilling, countryBilling,
            postBilling, telephoneBilling, mailBilling, firstNameDelivery, lastNameDelivery, addressDelivery,
            cityDelivery, countryDelivery, postDelivery, telephoneDelivery, mailDelivery', 'required'),
        array('active', 'numerical', 'integerOnly'=>true),
    );
}

在我看来我有类似的东西

    <tr>
        <td>
            <p><?php echo $form->label($model,'telephoneBilling'); ?><span>:&nbsp;</span><span class="required">*</span></p>
        </td>
        <td>
            <?php echo $form->textField($model,'telephoneBilling'); ?>
            <?php echo $form->error($model,'telephoneBilling'); ?>
        </td>
    </tr>
</table>

<p><?php echo $form->checkBox($model,'active', array('class' => 'change')); ?>
    Delivery information: Please check the box if your delivery address differs from your billing address and enter the
    required delivery address in the fields provided below.</p>

    <div id="deliveryFormWrapper" style="display: none">
    <table class="cartReviewTable">
    <tr>
        <td colspan="4">
            <span class="blueTitle"><?php echo CHtml::encode(Yii::t('app', 'Delivery Information ')); ?></span>
        </td>
    </tr>
    <tr>
        <td>
            <p><?php echo $form->label($model,'firstNameDelivery'); ?><span>:&nbsp;</span><span class="required">*</span></p>
        </td>
        <td>
            <?php echo $form->textField($model,'firstNameDelivery'); ?>
            <?php echo $form->error($model,'firstNameDelivery'); ?>
        </td>

这只是给你一张照片的一部分,所以当我点击复选框时我会显示这个隐藏的div,并且他有他的字段的规则(第一个div包含Billing字段,隐藏包含交付字段。

当我想提交表单并且没有选中复选框时,我不能这样做,因为必填字段,所以我在徘徊 是否有任何机会为这种情况使用场景以及如何,我需要一个线索。

谢谢,我希望你能理解我的问题。

1 个答案:

答案 0 :(得分:10)

是的,可能。在控制器中,您可以选中是否选中复选框,然后设置方案。像这样的东西

  if($_POST['my_checbox']==1)
   $model->setscenario('checked');  

然后只需$model->validate()检查错误。 在您的模型规则中,只需为您拥有的方案设置验证器:

array('delivery, firstNameBilling, lastNameBilling, addressBilling, cityBilling, countryBilling,
            postBilling, telephoneBilling, mailBilling, firstNameDelivery, lastNameDelivery, addressDelivery,
            cityDelivery, countryDelivery, postDelivery, telephoneDelivery, mailDelivery', 'required','on'=>'checked'),

多数民众赞成。很简单。