How to display simple user messages on a site using the Yii 2 framework.
A bit of theory
Flash messages in this case are notifications displayed to the user at any events.
Yii 2 already has a built-in mechanism for working with flash messages. It works on this principle:
- Use the
\Yii::$app->session->addFlash()method to add the message to the session.
- The message in the session is stored until it is from there extracted by the
- Once the message is extracted, it is deleted from the session.
Implementation of flash messages
Next, the basic application template provided by Yii 2 will be used as the code base. How to install the basic application template is described in this article.
Now we implement flash messages in practice. In this example, the simplest user notifications are considered, without any animations, etc. These notifications will be displayed at the top of the site before the rest of the content is displayed.
First, create an auxiliary view script, in which we place the code outputting the flash message. To do this, create a file
\views\layouts\main\flashes.phpwith the following content:
<?php foreach(Yii::$app->session->getAllFlashes() as $type => $messages): ?> <?php foreach($messages as $message): ?> <div class="alert alert-<?= $type ?>" role="alert"><?= $message ?></div> <?php endforeach ?> <?php endforeach ?>
- Next, you need to render the newly created view script
flashes.phpin the layout
- Now you can check how the flash messages work, for this, in the controller
\controllers\SiteController.phpwe add the following lines of code:
- Refresh the page in the web-browser and see the result:
In general, this is not a complete implementation of flash messages. Because now they are displayed each time the main page is refreshed. In real applications flash messages are displayed only after some actions, and then disappear. For example, we can display a flash message after user registration, that he needs to confirm his e-mail address, this message is sufficient to display only once after which it should disappear.