You are here
Home > Yii Framework > How To Set Flash Message In Yii Framework 2

How To Set Flash Message In Yii Framework 2

This short how-to article will help you in how to set flash message in Yii framework

The basic Yii application uses the setFlash() method in displaying messages to the user. These messages could be either success confirmation, error information and notice message. A lot many times in the controller you might have seen the below code.

and in the view file:

The above code is generally used for showing success messages within the yii application. However, there is an easy way to customize this behavior, so we can also display errors and notices.

Solution 1: Magical # char

In the controller:

and in the view:

Now, according to what is a boolean value of $overall_result (where of course we can put any checking, we want), user will see either success confirmation or error message.

The above (view) code also takes care of situation if there isn’t any # char in the flash. If so, it displays whole flash message with flash-success class, assuming that there is no class definition, if there is no # char.

Solution 2: Own function

We can write our own functions like this:

And user can specify in htmlOptions, which class to use in displaying text (flash-success, flash-error, flash-notice, all found in main.css, used by default Yii application or any other user-defined class).

This solution is easier, but it does not make any use of build in flashing feature. I.e. developer has to take his own care for transferring such message from the controller to a view.

In the controller:

and in the view file we can write like this:

Top