1

I need to compare 2 attribute value in the model and only if first value is lower than second value form can validate.I try with below code but it not worked.

controller

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,
        ]);
     } 
}

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']
    ];
}
}

It's going in to the validator function but not add the error like i wanted

$this->addError($attribute, 'Credit amount should less than Bill amount');

anyone can help me with this?

Rumes Shyaman
  • 1,072
  • 1
  • 15
  • 30

5 Answers5

3

If the validation is not adding any error, it's most likely being skipped. The issue is most likely becasue of default rules behaviour whereby it skips empty or already error given values as per here: https://www.yiiframework.com/doc/guide/2.0/en/input-validation#inline-validators

Specifically:

By default, inline validators will not be applied if their associated attributes receive empty inputs or if they have already failed some validation rules. If you want to make sure a rule is always applied, you may configure the skipOnEmpty and/or skipOnError properties to be false in the rule declarations.

So you would need to set up the skipOnEmpty or skipOnError values depending on what works for you:

[
    ['country', 'validateCountry', 'skipOnEmpty' => false, 'skipOnError' => false],
]
friek108
  • 1,064
  • 1
  • 12
  • 23
2

Try this:

public function actionOpanningBalance(){

 $model = new Bill();
 if ($model->load(Yii::$app->request->post()) && $model->validate()) {
    $model->created_at = \Yii::$app->user->identity->id;
    $model->save();
  }else{
   return $this->render('OpanningBalance', [
        'model' => $model,
    ]);
 } 
}

For Validation

You can use anonymous function :

['credit_amount',function ($attribute, $params) {
            if ($this->$attribute > $this->bill_amount)) {
                $this->addError($attribute, 'Credit amount should less than Bill amount.');
              return false;
            }
        }],
Insane Skull
  • 9,220
  • 9
  • 44
  • 63
0

you can use like this below answer is also write

public function rules(){
    return [
        ['credit_amount','custom_function_validation', 'on' =>'scenario'];
}
public function custom_function_validation($attribute){
    // add custom validation
    if ($this->$attribute < $this->cash_amount) 
        $this->addError($attribute,'Credit amount should less than Bill amount.');
}
Amitesh Kumar
  • 3,051
  • 1
  • 26
  • 42
0

I've made custom_function_validation working using 3rd params like this:

public function is18yo($attribute, $params, $validator)
{
    $dobDate = new DateTime($this->$attribute);
    $now = new DateTime();
    if ($now->diff($dobDate)->y < 18) {
        $validator->addError($this, $attribute, 'At least 18 years old');
        return false;
    }
}
0

This is a back end validation and it will trigger on submit only. So you can try something like this inside your validation function.

if (!$this->hasErrors()) {
  // Your validation code goes here.
}

If you check the basic Yii2 app generated you can see that example in file models/LoginForm.php, there is a function named validatePassword.

Validation will trigger only after submitting the form.

Krishnadas PC
  • 5,981
  • 2
  • 53
  • 54