Yii框架——不同的验证规则取决于选择的选项


Yii framework - Different validation rules depending on selected options

是否有可能创建依赖于选择的模型规则?

我有一个"存款"模型,用于输入汇款详细信息,我有一个下拉列表,有两个可能的选择"现金转账","支票转账",我有字段cash_deposit_date,bank_name..只需要现金转账和checke_date, checke_no和in_favor_of。这只在支票转账时需要。我该怎么做呢?

我知道我可以使用这样的场景,

$model=new Deposit("cash_transfer");

$model=new Deposit("cheque_transfer");

但是我如何根据下拉列表中选择的值更改场景?

你就不能这样做吗:

生成的HTML:

<form>
....
<select name="scenario">
    <option value="cash_transfer">Cash Transfer</option>
    <option value="cheque_transfer">Checque Transfer</option>
</select>
....
</form>
代码:

// allow only lowercase letters and underscore
$scenario = preg_replace('/[^a-z_]/', '', $_POST['scenario']);
if (!empty($scenario)) {
    $model = new Deposit($scenario);
} else {
    die('Missing scenario!');
}

从jupaju答案延伸,

下拉列表也是一个模型字段(transfer_type),所以我做了这样的事情。检查POST值设置后,使用$model->scenario = $model->transfer_type==1 ? 'cash_transfer':'cheque_transfer'更改场景

我的代码是

$model=new Deposit;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Deposit']))
{
    $model->attributes=$_POST['Deposit'];
    $model->scenario = $model->transfer_type==1 ? 'cash_transfer':'cheque_transfer';    
    if($model->save())
        $this->redirect(array('admin'));
}
$this->render('create',array('model'=>$model));

我认为最好的方法是在你的模型中使用个性化的验证规则,然后检查模型的"scenario"属性是否被设置为一个或另一个选项。

你可以在这里阅读更多关于自定义验证规则

希望这对你有帮助。好运!

这样比较简单

在你的模型中放:

public $pay_type;
/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        ...
        array('pay_type', 'required'),
        array('cash_deposit_date', 'validationTransfer'),
        ...
    );
}
public function validationTransfer($attribute,$params)
{
     // this a sample, put all your need
     if($this->pay_type=='cash_transfer' and $this->cash_deposit_date==='')
          $this->addError('cash_deposit_date','If you will pay to Cash Transfer, enter your cahs deposit date');
     // this a sample, put all your need
     if($this->pay_type=='cheque_transfer' and $this->cheque_date==='')
          $this->addError('cheque_date','If you will pay to Cheque Transfer, enter your cheque date');
     // this a sample, put all your need
     if($this->pay_type=='cheque_transfer' and $this->cheque_no==='')
          $this->addError('cheque_no','If you will pay to Cheque Transfer, enter your Cheque No');
}

<?php echo $form->labelEx($model,'pay_type',array('class'=>'control-label')); ?>
<?php echo $form->dropDownList($model,'pay_type',array("cash_transfer"=>"Cash Transfer","cheque_transfer"=>"Cheque Transfer"),array('class'=>'form-control','empty'=>'Pay Type...')); ?>
<?php echo $form->error($model,'pay_type',array('class'=>'help-block')); ?>
注意:像"help-block","control-label","form-control"这样的css类在witget form上是可选的,也许你使用Bootstrap 3,它会看起来很好