How to work with flash messages

You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#2)next (#4) »

A flash message is used in order to keep a message in session and make sure it’s removed from session after it has been displayed to the user. Therefore flash messages are available only in the current and the next requests. Flash messages can be set using the setFlash() Method of [CWebUser]. For example if you would like to inform the user, that his changes were successfully saved, you could add the following line to your Controller:

Yii::app()->user->setFlash('success',"Data saved!");

In this example we used the key 'success'. If you want to define more than one flash messages, you will have to use different keys. To check for flash messages we use the hasFlash() Method and to obtain the flash message we use the getFlash() Method. So showing of the flash message in a view is done by

<?php if(Yii::app()->user->hasFlash('success')):?>
    <div class="info">
        <?php echo Yii::app()->user->getFlash('success'); ?>
    </div>
<?php endif; ?>

These few lines of code will make a flash message with the key "success" visible to the user within a div of class "info". The message will be displayed until this or another page is (re)loaded in the browser.

If you want the flash message to appear somewhere above the content and then automatically fade out after a few seconds, you will have to add the following lines to your view:

<?php
Yii::app()->clientScript->registerScript(
   'myHideEffect',
   '$(".info").animate({opacity: 1.0}, 3000).fadeOut("slow");',
   CClientScript::POS_READY
);
?>

With these lines of code we register a piece of jQuery (already included with YII) javascript code, using 'myHideEffect' as ID. It will be inserted in the jQuery's ready function (CClientScript::POS_READY). Due to the chainablity of jQuery the little script will run two effects on the .info DIV sequentially:

.animate({opacity: 1.0}, 3000)

Normally this would animate the .info DIV to a full opacity within 3 seconds. But the DIV is already rendered with full opacity upon page load, so calling this effect will just cause a delay for 3 seconds.

.fadeOut("slow")

This is the fadeOut effect which will hide the .info DIV at slow speed.

More information about the jQuery effects can be found here.

Links

Chinese version

51 0
40 followers
Viewed: 390 062 times
Version: Unknown (update)
Category: Tutorials
Written by: pfth
Last updated by: François Gannaz
Created on: Mar 5, 2009
Last updated: 13 years ago
Update Article

Revisions

View all history

Related Articles