B
B
balex7772020-01-21 11:53:28
Yii
balex777, 2020-01-21 11:53:28

Output authorization errors in yii2 modal window, how to do?

I have an authorization and registration form in a modal window (it doesn’t matter how it’s done, but for those who are interested through a widget)
It is necessary that when entering a login and password, it would display an error, incorrect login (under the login field) or incorrect password (under the password field) after clicking on the login button
In the standard LoginForm, only the password is validated, in order for the login to be validated, I created a method

public function validateUsername($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user) {
                $this->addError($attribute, 'Не правильный логин.');
            }
        }
    }

well, added to the rules

// username is validated
['username', 'validateUsername'],

Now if you click on an incorrect login, the controller redirects to site/login, where under the login field it displays an error that the login is not correct, and the same for the password.
In general, it is necessary that the controller does not redirect to the site/login page, but gives an error immediately in the model window.
Here is the standard Login action itself
public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        }
        else {
            $model->password = '';

            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

So I’m thinking where to start and how to properly render in else, although $model->login() itself produces a bool, but how is the same validation errors passed here
return $this->render('login', [
                'model' => $model,
            ]);

This means that you can render just an error on the modal window, how to do it? who faced?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Kim, 2020-01-21
@kimono

You need client-side validation:
https://www.yiiframework.com/doc/guide/2.0/en/inpu...
, or ajax validation of the entire form before submitting:
https://github.com/yiisoft/yii2 /issues/1399#issuec...

S
Sergey Desh, 2020-01-28
@serdesh

As an option. After an unsuccessful login, you need to re-open the modal login form, but before rendering the form (widget), validation errors must be passed to the LoginForm() model.
For example:

$model->addError('username', 'Не верный логин пользователя');
return $this->render('login', [
                'model' => $model,
            ]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question