S
S
Sergey2015-03-30 01:52:55
JavaScript
Sergey, 2015-03-30 01:52:55

How to do Ajax validation in Yii2?

There are two tables user, orders
For example, the client wants to withdraw money, but he does not have them.
How to do with Ajax, so that when you enter an amount less than what is on his balance sheet, it gives an error.
The task is not difficult, but this is my first yii project.
How to properly write a database check?

Here is the form with the amount field.

<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'sum')->textInput(['maxlength' => 255]) ?>
<div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? Yii::t('frontend', 'Create') : Yii::t('frontend', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>


Controller, cleaned from excess, to make it clearer
public function actionCreate()
    {
            $model = new Orders();

            if ($model->load(Yii::$app->request->post())) {
                $model->save();
                return $this->redirect(['view', 'id' => $model->order_id]);
            } else {
                return $this->render('create', [
                    'model' => $model,
                ]);
            }
    }


Please post an example.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Frank, 2015-03-30
@alekskondr

Does the standard field validation work according to the rules in the model?
If so, then the example below should help you:

public function rules()
{
  return array(
    array(array('password','confirmpassword'), 'required'),
    array('password', 'validatePasswordEquals'),
  );
}
 
//Кастомная функция для проверки паролей
public function validatePasswordEquals()
{
  if($this->password!=$this->confirmpassword) {
    $errorMsg= 'Passwords must be equal.';
    $this->addError('confirmpassword',$errorMsg);
  }
  if(strlen($this->password)<=8) {
    $errorMsg= 'Password must be at least 8 symbols length';
    $this->addError('password',$errorMsg);
  }
}

You add a new rule, for example
And then just add a new checkMoney method, with the check functionality you need :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question