是否可以创建依赖于选择的模型规则?
我有一个模型“存款”,用于输入汇款详情..我有下拉列表,有两个可能的选择“现金转账”,“支票转账”,我有字段cash_deposit_date,bank_name ..只需要现金转账和cheque_date,cheque_no和in_favour_of ..只有在支票转账时才需要..我怎么能这样做..?
我知道我可以使用这样的场景,
$model=new Deposit("cash_transfer");
或
$model=new Deposit("cheque_transfer");
但是如何根据下拉列表中选择的值更改方案?
答案 0 :(得分:2)
你能不能这样做:
生成的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!');
}
答案 1 :(得分:1)
从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));
现在它正在运作..
答案 2 :(得分:0)
答案 3 :(得分:0)
这比我更简单
在您的模型中:
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')); ?>
注意:在witget表单上的“help-block”,“control-label”,“form-control”等css类是可选项,也许你使用Bootstrap 3它看起来不错