H
H
hollanditkzn2017-09-04 10:38:09
Yii
hollanditkzn, 2017-09-04 10:38:09

How to implement a validation that checks a condition from 2 models?

I need to check if a model exceeds a given attribute and should not exceed another model's attribute. That is, in one model there is only how much the order costs $oplata, and in the second model there is how much the amount was paid, that is, the financial report $sum.
I need the amount not to exceed the cost of the order, to do the validation I did it
as follows

public function actionDraft($id)
    {
        $model = $this->findModel($id);//Модель заказа
        $financy = new Financy();//модель финансы, доходи рсход

        if ($financy->load(Yii::$app->request->post()) && $financy->validate()){
            if (!$financy->save()){
                print_r($financy->getErrors());//Если не прошла проверку выводит ошибку
            } else {
                $model->fact_oplata = $model->fact_oplata + $financy->sum;//фактически сколько заплатили за заказ + с суммой внесений. То есть может вначале была предоплата, а в конце клиент полностью оплатил сумму
                if ($model->oplata === $model->fact_oplata){//если все ровно, то проводит заказ на закрытие
                    $model->action = 0;
                    $model->save();
                    Yii::$app->session->addFlash('update', 'Заказ был закрыт');
                } else {//Если нет, то выводит ошибку в валидации, вот тут у меня ступор получился
                    $financy->addError('Сумма не должно превышать всего');//создает ошибку
                    print_r($financy->getErrors());//выводит ошибку
                }
            }
            return $this->redirect(['admin']);
        }

        return $this->renderAjax('draft', [
            'model' => $model,
            'financy' => $financy,
        ]);
    }

Tried to do it like this throw new NotFoundHttpException('The amount must not exceed everything');
It just doesn't quite fit.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2017-09-04
@hollanditkzn

And why do you have an action validating, and not a model? Here is a validator for this:
www.yiiframework.com/doc-2.0/yii-validators-compar...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question