<?= $form->field($userRole, 'userid', ['options' =>['class' => 'bigDiv'] ])->textInput(['placeholder'=> 'ccc', 'class'=> 'inputSelf', 'maxlength' => true, 'value' => $user->id]) ?>
//add time 2019-04-26 start
今天需要做一个前台的简单的表单
使用yii2自带的Form控件验证,提交完后刷新页面,然后alert出成功或者失败
首先在前台页面
<?php $form = ActiveForm::begin([
'enableClientValidation' => true,
'options' => ['enctype' => 'multipart/form-data', 'class' => 'navbar-form navbar-left'],
'action' => Url::to(['form/dingyue']),
'enableAjaxValidation' => true,
// 'validationUrl' => Url::to(['form/index']),
]); ?>
<?= $form->field($model, 'username')->textInput(['placeholder' => '您的姓名', 'require' => 'true','class' => 'form-control ', 'maxlength' => 255])->label(false) ?>
<?= $form->field($model, 'email')->textInput(['placeholder' => '您的邮箱地址', 'require' => 'true', 'class' => 'form-control', 'maxlength' => 255])->label(false) ?>
<div class="form-group">
<?= Html::submitButton('提交', ['class' => 'btn btn-blue-bg-new']) ?>
<div class="help-block"></div>
</div>
<?php ActiveForm::end(); ?>
这样写好后后台直接上代码
$model = new Form;
$model->scenario = 'dingyue';
if($model->load(Yii::$app->request->post())){
if(Yii::$app->request->isAjax){
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}else{
if ($model->save()) {
$this->flash('success', '提交成功!');
return $this->redirect(Yii::$app->request->referrer);
} else {
$this->flash('error', Yii::t('easyii', 'Create error. {0}', $model->formatErrors()));
return $this->refresh();
}
}
}
这样写完后会在系统的session中存一个success或者是error的信息,如果不做下面操作,那么呈现的效果表单提交,页面刷新
这时候用户无法知道自己是否已经提交成功或者失败,需要在页面增加一块代码
<script>
<?php foreach(Yii::$app->session->getAllFlashes() as $key => $message) : ?>
alert('<?=$message?>');
<?php endforeach; ?>
</script>
以上5行代码的意思是:如果后台设置了flash,那么前台页面就把提示的信息alert出来
//add end