在我的模态框中,我想检查唯一的电子邮件,这只能在提交表单后才能完成。当我触发提交按钮时,控制器操作将发送给我在控制器中创建操作,因为它将返回唯一的电子邮件地址错误。我希望在模式框中显示此错误。所以我使用了Ajax提交。以下是我的代码。
我的表单
<?php yii\widgets\Pjax::begin(['class' => 'new_projects']) ?>
<?php $form = ActiveForm::begin([
'action' => ['create'],
'options' => ['class' => 'form-horizontal disable-submit-buttons', 'id'=> 'projectsId'],
'fieldConfig' => [
'template' => "<div class=\"row .field-register-email\">
<div class=\"col-xs-6 .help-block\">{label}</div>\n<div class=\"col-xs-6 text-right\">{hint}</div>
\n<div class=\"col-xs-12 \">{input}</div>
</div>",
],
]); ?>
<?= $form->errorSummary($model, $options = ['header'=>'']); ?>
<?= $form->field($model, 'user_fname')->textInput(['class'=>'form-control']);?>
<?= $form->field($model, 'user_lname')->textInput(['class'=>'form-control']); ?>
<?= $form->field($model,'user_email',['enableAjaxValidation'=> 'true'])->textInput(['class'=>'form-control']); ?>
<?= $form->field($model, 'user_password_hash')->passwordInput([]); ?>
<?= $form->field($model, 'user_password_hash_repeat')->passwordInput(['class'=>'form-control']); ?>
<?php $items = ArrayHelper::map(SimAuthAssignment::find()->all(),'item_name' ,'item_name');?>
<?= $form->field($mode, 'item_name')->dropDownList($items,[]);?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php yii\widgets\Pjax::end() ?>
我的控制器创建操作
public function actionCreate()
{
$model = new SimUser(['scenario' => SimUser::SCENARIO_CREATE]);
$mode = new \app\modules\auth\models\SimAuthAssignment();
if ($model->load(Yii::$app->request->post()) && $mode->load(Yii::$app->request->post())){
\Yii::$app->response->format = Response::FORMAT_JSON;
$model->setPassword($model->user_password_hash);
$model->generateAuthKey();
$model->company_id = Yii::$app->user->identity->company_id;
if (!$model->save()){
($model->load(Yii::$app->request->post()) && $model->validate());
}
else{
$auth = Yii::$app->authManager;
$authorRole = $auth->getRole($mode->item_name);
$auth->assign($authorRole, $model->getId());
echo BaseJson::encode(array(
"status"=>true,
"message"=>"Created Project $model->name Successfully",
));
}
// return $this->redirect(['index']);
}
return $this->renderAjax('create', [
'model' => $model,
'mode' => $mode,
]);
}
Js档案
$(document).on("beforeSubmit", "#projectsId", function () {
// submit form
$.ajax({
url : $("#projectsId").attr('action'),
type : 'post',
data : $("#projectsId").serialize(),
success: function(response)
{
alert("success");
$.pjax.reload({container:"#projectsGrid"});
$('#modal').modal("hide");
},
error : function (response)
{
alert("failure");
console.log('internal server error');
}
});
return false;
// Cancel form submitting.
});
我如何在模态框中出错。即使有错误,也会触发警报(&#34;成功&#34;)。如果没有唯一的电子邮件,它就完美无缺。我想弄清楚如何让错误到模态框。 感谢!!!
答案 0 :(得分:1)
在您的控制器中更改代码,如下所示:
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select * from user where email= '$email'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Email: ". $row["email"] . "<br>";
}
} else {
echo "0 results";
}
和你的js文件添加yii表单验证脚本:
use yii\bootstrap\ActiveForm;
public function actionCreate()
{
$model = new SimUser(['scenario' => SimUser::SCENARIO_CREATE]);
$mode = new \app\modules\auth\models\SimAuthAssignment();
if ($model->load(Yii::$app->request->post()) && $mode->load(Yii::$app->request->post())){
\Yii::$app->response->format = Response::FORMAT_JSON;
$model->setPassword($model->user_password_hash);
$model->generateAuthKey();
$model->company_id = Yii::$app->user->identity->company_id;
if ($model->validate()){
$model->save();
$auth = Yii::$app->authManager;
$authorRole = $auth->getRole($mode->item_name);
$auth->assign($authorRole, $model->getId());
echo BaseJson::encode(array(
"status"=>'true',
"message"=>"Created Project $model->name Successfully",
));
}
else{
$model=ActiveForm::validate($model);
return['status'=>'false','errors'=>$model];
}
// return $this->redirect(['index']);
}
return $this->renderAjax('create', [
'model' => $model,
'mode' => $mode,
]);
}
了解更多参考资料https://github.com/samdark/yii2-cookbook/blob/master/book/forms-activeform-js.md