Yii 2 - Displaying flash (users) messages on the site


Yii 2 - Displaying flash (users) messages on the site 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:

  1. Use the \Yii::$app->session->addFlash() method to add the message to the session.
  2. The message in the session is stored until it is from there extracted by the Yii::$app->session->getAllFlashes() method.
  3. 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.

  1. 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.php with 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 ?>
  2. Next, you need to render the newly created view script flashes.php in the layout \views\layouts\main.php:

Yii 2 - Displaying flash (users) messages on the site

  1. Now you can check how the flash messages work, for this, in the controller \controllers\SiteController.php we add the following lines of code:

Yii 2 - Displaying flash (users) messages on the site

  1. Refresh the page in the web-browser and see the result:

Yii 2 - Displaying flash (users) messages on the site


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.