YII2活动表单显示自定义验证消息 [英] YII2 Active Form show custom validation message
问题描述
我有一个登录表单,用于在其中实现集成twilio API的2因子身份验证.
I have login form which, where I am implementing 2 Factor Authentication integrating twilio API.
API运行正常,我可以获取成功或失败的验证响应.
The API is working fine and I can get the verification response for success or failure.
现在,我无法以某种方式显示消息"OTP验证失败".在表格上.
Now I am somehow not able to display the message "OTP verification Failed" on the form.
这是我的控制器代码:
公共功能actionLogin(){
public function actionLogin() {
$this->layout = '@app/themes/backend/login';
$model = new LoginForm(['scenario' => 'login']);
if (Yii::$app->request->isAjax && $model->load($_POST)) {
$authy_id = Yii::$app->session->get('authy_id');
// var_dump($authy_id);exit;
Yii::$app->response->format = 'json';
// var_dump($model);exit;
if(!empty($authy_id)){
$authy_api = new AuthyApi('api-key');
$token_entered_by_user = $model->otp;
$verification = $authy_api->verifyToken($authy_id, $token_entered_by_user);
if ($verification->ok()) {
// correct token
// Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($model);
}else{
// Yii::$app->response->format = 'json';
$model->addError('OTP Verification Failed');
print_r('error');
Yii::$app->session->setFlash('error', "OTP verification failed!");
exit;
}
}else{
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($model);
}
}
if ($model->load(Yii::$app->request->post()) && $model->login()) {
if (Yii::$app->user->identity->user_role == 'admin') {
$path = "../" . Yii::$app->user->identity->user_role;
return $this->redirect($path);
}
elseif(Yii::$app->user->identity->user_role == 'customer') {
$path = "../" . Yii::$app->user->identity->user_role .'/default/index';
return $this->redirect($path);
}
else{
$path = "../" . "site/index";
return $this->redirect($path);
...
}
}
return $this->render('login', [
'model' => $model,
]);
}
在我的查看文件中,我尝试过:
and in my view file I have tried like:
<?php pjax::begin(['id'=>'otp-error']); ?>
<?php if(Yii::$app->session->hasFlash('error')):?>
<div class="info" id="otp-error">
<?= Yii::$app->session->getFlash('error') ?>
</div>
<?php endif?>
<?php pjax::end(); ?>
我在这里想念什么?
推荐答案
在设置"OTP验证失败!"后删除 exit;
.消息.
Remove the exit;
after setting the "OTP verification failed!" message.
设置了该即时消息后,您将无所事事.
You are returning to nowhere just after you set that flash message.
请记住,要使Flash消息正常工作,您的代码必须到达您的视图.如果您之前返回或返回JSON,则它将永远不会到达您的客户端.
Remember that for the flash message to work, your code must reach your view. If you return before, or return a JSON, it will never get to your client.
这篇关于YII2活动表单显示自定义验证消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!