How to set and get a flash message in Yii2?
Details
In Yii2, you can set a flash message to display temporary messages to the user. Flash messages are typically used to provide feedback or notifications after an action is performed, such as after a form submission or a successful update. Here's how you can set a flash message in Yii2:
// Setting a success flash message Yii::$app->session->setFlash('success', 'Your success message goes here.'); // Setting an error flash message Yii::$app->session->setFlash('error', 'Your error message goes here.'); // Setting a warning flash message Yii::$app->session->setFlash('warning', 'Your warning message goes here.'); // Setting an info flash message Yii::$app->session->setFlash('info', 'Your info message goes here.');
You can use these lines of code in your controllers or actions to set flash messages of different types (success, error, warning, and info). The first parameter to setFlash is the message type, and the second parameter is the message text.
To display these flash messages in your view, you can use the following code:
use yii\bootstrap\Alert; // Display success flash message if (Yii::$app->session->hasFlash('success')) { echo Alert::widget([ 'options' => ['class' => 'alert-success'], 'body' => Yii::$app->session->getFlash('success'), ]); } // Display error flash message if (Yii::$app->session->hasFlash('error')) { echo Alert::widget([ 'options' => ['class' => 'alert-danger'], 'body' => Yii::$app->session->getFlash('error'), ]); } // Display warning flash message if (Yii::$app->session->hasFlash('warning')) { echo Alert::widget([ 'options' => ['class' => 'alert-warning'], 'body' => Yii::$app->session->getFlash('warning'), ]); } // Display info flash message if (Yii::$app->session->hasFlash('info')) { echo Alert::widget([ 'options' => ['class' => 'alert-info'], 'body' => Yii::$app->session->getFlash('info'), ]); }
This code checks if flash messages of each type are set and, if so, displays them using the Alert widget with appropriate CSS classes for styling.
Make sure you have the Yii2 Bootstrap extension or a similar package installed to use the Alert widget.