Setting flash message
A flash message is used in order to keep a message in session through one or several requests of the same user. By default, it is removed from session after it has been displayed to the user.
Flash messages can be set using the setFlash() Method
Add below code in your controller
file like:
Yii::$app->session->setFlash('success', "Your message to display.");
Example:
class ProductsController extends \yii\web\Controller
{
public function actionCreate()
{
$model = new User();
if ($model->load(Yii::$app->request->post())) {
if ($model->save()) {
Yii::$app->session->setFlash('success', "User created successfully.");
} else {
Yii::$app->session->setFlash('error', "User not saved.");
}
return $this->redirect(['index']);
}
return $this->render('create', [
'model' => $model
]);
}
}
Displaying flash message
To check for flash messages we use the hasFlash() Method and to obtain the flash message we use the getFlash() Method.
By default, fetching a message deletes it from the session. This means that a message is meant to be displayed only on the first page served to the user. The fetching methods have a boolean parameter that can change this behavior.
So showing of the flash message defined above in a view
is done by
// display success message
<?php if (Yii::$app->session->hasFlash('success')): ?>
<div class="alert alert-success alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
<h4><i class="icon fa fa-check"></i>Saved!</h4>
<?= Yii::$app->session->getFlash('success') ?>
</div>
<?php endif; ?>
// display error message
<?php if (Yii::$app->session->hasFlash('error')): ?>
<div class="alert alert-danger alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
<h4><i class="icon fa fa-check"></i>Saved!</h4>
<?= Yii::$app->session->getFlash('error') ?>
</div>
<?php endif; ?>