我知道这是一个愚蠢的问题,但我刚开始学习Yii2。我还没有找到与此相关的任何有用信息,所以。如果用户已成功添加到数据库,我需要做的是显示一条消息。 somoene可以帮助我解决这个问题吗?我不知道它必须写在哪里:model
,controller
或view
。
这是我的controller action
:
public function actionCreate()
{
$model = new Employee();
$model->scenario = Employee::SCENARIO_CREATE;
$post = Yii::$app->request->post();
if ($model->load($post) && $model->save()) {
return $this->redirect(['create']);
}
return $this->render('create', [
'model' => $model,
]);
}
这是我的view
:
<div class="employee-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->textInput([
'maxlength' => 50,
]) ?>
<?= $form->field($model, 'surname')->textInput([
'maxlength' => 50,
]) ?>
<?= $form->field($model, 'employment_date')->textInput() ?>
<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>
现在发生的事情是脚本不允许输入日期,该日期晚于今天的日期,也不允许在日期字段中输入字符串。所以要明确的是,如果用户输入了正确的信息,我需要添加一条消息,说明&#34;用户已成功输入数据库&#34;。
感谢您的帮助!
答案 0 :(得分:1)
在控制器中设置闪光信息。如下。
Yii::$app->session->setFlash('flashMsg', 'flash Msg or any kind of content like variables');
并在您的视图页面中显示此消息。如下。
<?php if (Yii::$app->session->hasFlash('flashMsg')){ ?>
<div class="alert alert-success">
<!-- flash message -->
<?php Yii::$app->session->getFlash('flashMsg'); ?>
</div>
<?php } ?>
答案 1 :(得分:0)
您可以在控制器中使用Yii::$app->session->setFlash
方法,而无需在视图中添加任何内容:
public function actionCreate()
$model = new Employee();
$model->scenario = Employee::SCENARIO_CREATE;
$post = Yii::$app->request->post();
if ($model->load($post) && $model->save()) {
Yii::$app->session->setFlash('success', 'User added');
return $this->redirect(['create']);
}
else {
Yii::$app->session->setFlash('error', 'Error adding user');
}
return $this->render('create', [
'model' => $model,
]);
}