How can I show error message in login form modal?

2019-09-17 16:45发布

问题:

I am following this link to create a login modal. Now my login action is

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{
        return $this->renderAjax('login', [
                'model' => $model,
        ]);         
    }
}

and in another view test.php, I have a button

echo Html::button('Create New Company',
                  ['value' => Url::to(['site/login']),
                   'title' => 'Creating New Company', 
                   'class' => 'showModalButton btn btn-success'
                  ]
                ); 

On clicking this button, it is showing the login form as modal and doing client side validation for required attributes. When correct username and password is provided, the user gets successfully logged in too.

My problem is when we pass the wrong credential's for username or password, it is rendering site/login in another page which is unstyled and showing error Incorrect username or password there. How can I show that error on modal?

回答1:

Use ajax validation like below

In form

'enableAjaxValidation' => true,

In controller action use below code

if (Yii::$app->request->isAjax && $model->load($_POST))
{
  Yii::$app->response->format = 'json';
  return \yii\widgets\ActiveForm::validate($model);
}


标签: ajax yii2