yii: set and display generic global message

by prettyscripts on 2011-03-04 14:28

phpcssyii

Yii has flash messages that's stored in session variables and is available in current and next requests. eg you have error or success message that you want to inform user when the page is redirected.

for some basic understanding, please read how to work with flash messages.

basic functions you need to know:

currently (v116) templates generated by yiic does not include flash messages and controllers does not include calls to set flash messages. however the default style sheet (in main.css) include style classes flash-error, flash-success, flash-notice.

displaying message

for displaying global message, it's easier to define in the main template. edit /path/to/protected/views/layouts/main.php (if theme is used, edit /path/to/web/themes/yourtheme/views/layouts/main.php), add the following code (lines 3 to 9) before displaying content:

PHP:

<body>
    ....
    <?php foreach(array('error''notice''success') as $key): ?>
        <?php if (Yii::app()->user->hasFlash($key)): ?>
            <div class="flash-<?php echo $key ?>">
                <?php echo Yii::app()->user->getFlash($key?>
            </div>
        <?php endif; ?>
    <?php endforeach; ?>
 
    <?php echo $content?>
    ....
</body>

for the sake of simplicity, when setting flash messages, use 'error', 'notice' and 'success' as key. this ensure a well styled message is displayed. otherwise, remember to define styles for different keys.

setting message

this is set in controller. here's example modifying login action.

PHP:

public function actionLogin() {
    $model = new LoginForm();
 
    if (isset($_POST['ajax']) && $_POST['ajax'] == 'login-form') {
        echo CActiveForm::validate($model);
        Yii::app()->end();
    }
    try {
        if (isset($_POST['LoginForm'])) {
            $model->attributes $_POST['LoginForm'];
            if ($model->validate() && $model->login()) {
                Yii::app()->user->setFlash('success''You have successfully logged in!');
                $this->redirect(Yii::app()->user->returnUrl);
            }
        }
    }
    catch (Exception $e) {
        Yii::app()->user->setFlash('error',
            'Login Error: ' $e->getMessage() . ' (' $e->getCode() . ')');
    }
    $this->render('login'array('model' => $model));
}

notes:

  • line 8 and 17 to 20: add this to catch any exception errors.
  • line 9: set a successful message to be displayed in next page after redirection).
  • line 20: set error message.