How can I show error message in login form modal?

浪子不回头ぞ 提交于 2019-12-25 08:29:24

问题


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


来源:https://stackoverflow.com/questions/42408190/how-can-i-show-error-message-in-login-form-modal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!