【发布时间】:2015-12-02 11:21:23
【问题描述】:
我需要比较模型中的 2 个属性值,只有当第一个值低于第二个值时才能验证。我尝试使用下面的代码,但它不起作用。
控制器
public function actionOpanningBalance(){
$model = new Bill();
if ($model->load(Yii::$app->request->post())) {
$model->created_at = \Yii::$app->user->identity->id;
$model->save();
}else{
return $this->render('OpanningBalance', [
'model' => $model,
]);
}
}
型号
public function rules()
{
return [
[['outlet_id', 'sr_id', 'bill_number', 'bill_date', 'created_at', 'created_date','bill_amount','credit_amount'], 'required'],
[['outlet_id', 'sr_id', 'created_at', 'updated_at'], 'integer'],
[['bill_date', 'd_slip_date', 'cheque_date', 'created_date', 'updated_date','status'], 'safe'],
[['bill_amount', 'cash_amount', 'cheque_amount', 'credit_amount'], 'number'],
[['comment'], 'string'],
['credit_amount',function compareValue($attribute,$param){
if($this->$attribute > $this->bill_amount){
$this->addError($attribute, 'Credit amount should less than Bill amount');
}],
[['bill_number', 'd_slip_no', 'bank', 'branch'], 'string', 'max' => 225],
[['cheque_number'], 'string', 'max' => 100],
[['bill_number'], 'unique']
];
}
}
它进入了验证器函数,但没有像我想要的那样添加错误
$this->addError($attribute, 'Credit amount 应该小于 Bill amount');
谁能帮我解决这个问题?
【问题讨论】:
-
您只需致电
$model->validate()... -
你的意思是像 if($model->validate()){"save model"} 我做了但没用。
-
删除函数名
comparevalue.
标签: validation yii2 yii2-validation