Yii2 Flash Message

Learn how to use Yii2 Flash Message in basic and advanced template

Basically Flash message is a message that shows on the top of any page indicating any error, warning or success notification.

In Yii2 you can send Flash Message from controller to views along with custom message after setting it using session.

Set your Flash message before redirecting or rendering to any view with two parameters, 1st one will indicate type of message success or error and other parameter holds your message.

Here is how to achieve this.

\Yii::$app->session->setFlash('success', 'Article has been Created Successfully'); return $this->redirect(['view', 'id' => $id]); OR \Yii::$app->session->setFlash('error', 'Article could not be saved please check and submit again.'); return $this->render('create', [ 'model' => $model, ]); 1 2 3 4 5 6 7 8 9 \ Yii :: $ app -> session -> setFlash ( 'success' , 'Article has been Created Successfully' ) ; return $ this -> redirect ( [ 'view' , 'id' = > $ id ] ) ; OR \ Yii :: $ app -> session -> setFlash ( 'error' , 'Article could not be saved please check and submit again.' ) ; return $ this -> render ( 'create' , [ 'model' = > $ model , ] ) ;

If you are using Yii2 advanced template you will find a widget in your layout/main.php

?= Alert::widget() ?>

This Alert Widget will receive Flash Message and show according to parameters. If you want to show your flash message somewhere else just remove from your layout and call it in any other view.

If you are using Yii2 basic template you can use like this.

SetFlash() in Controller

\Yii::$app->session->setFlash('myMessage', 'Article has been Created Successfully'); 1 \ Yii :: $ app -> session -> setFlash ( 'myMessage' , 'Article has been Created Successfully' ) ;

Check if session hasFlash() Message

\Yii::$app->session->hasFlash('myMessage'); 1 \ Yii :: $ app -> session -> hasFlash ( 'myMessage' ) ;

Then getFlash() and show in View