【问题标题】:scenario for validation rules in yiiyii 中验证规则的场景
【发布时间】:2013-06-29 11:57:46
【问题描述】:

我在徘徊有没有机会使用场景作为规则,

在我的模型中我有

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 包含帐单字段,而隐藏的包含交付字段。

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

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

【问题讨论】:

标签: php validation yii scenarios yii-validation


【解决方案1】:

是的,这是可能的。在您的控制器中,您可以检查复选框是否选中,然后设置场景。类似的东西

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

然后只需执行$model-&gt;validate() 即可检查错误。 在您的模型规则中,只需为您拥有的场景设置验证器:

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

仅此而已。很简单。

【讨论】:

  • 谢谢ineersa,你帮了我很多:)
  • 场景用例的好例子
  • 太棒了。不错的用例:)
猜你喜欢
  • 2017-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多