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?

3
  • You should simply call $model->validate() ... Commented Dec 2, 2015 at 11:23
  • you mean add like if($model->validate()){"save model"} i did but not worked. Commented Dec 2, 2015 at 11:25
  • remove function name comparevalue. Commented Dec 2, 2015 at 12:19

5 Answers 5

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],
]
Sign up to request clarification or add additional context in comments.

Comments

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

5 Comments

Try with anonymous function: yiiframework.com/doc-2.0/…
i found out that $this->addError($attribute, 'Credit amount should less than Bill amount.'); not working
try adding: 'skipOnError' => false in rules.
have you removed function name compareValue?
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.');
}

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.