- Yii 1.1 Application Development Cookbook
- Alexander Makarov
- 268字
- 2021-04-02 18:41:02
Using flash messages
When you are editing a model with a form, when you are deleting a model, or doing any other operation, it is good to tell users if it went fine or if there was an error. Typically, after some kind of action, such as editing a form, a redirect will happen and we need to display a message on the page we want to go to. However, how to pass it from the current page to the redirect target and clean afterwards? Flash messages will help us.
Getting ready
Set up a new application using yiic webapp
.
How to do it...
- Let's create a
protected/controllers/WebsiteController.php
controller as follows:class WebsiteController extends CController { function actionOk() { Yii::app()->user->setFlash('success', 'Everything went fine!'); $this->redirect('index'); } function actionBad() { Yii::app()->user->setFlash('error', 'Everything went wrong!'); $this->redirect('index'); } function actionIndex() { $this->render('index'); } }
- Additionally, create the
protected/views/website/index.php
view as follows:<?php if(Yii::app()->user->hasFlash('success')):?> <div class="flash-notice"> <?php echo Yii::app()->user->getFlash('success')?> </div> <?php endif?> <?php if(Yii::app()->user->hasFlash('error')):?> <div class="flash-error"> <?php echo Yii::app()->user->getFlash('error')?> </div> <?php endif?>
- Now, if we go to
http://example.com/website/ok
, we'll be redirected tohttp://example.com/website/index
and a success message will be displayed. Moreover, if we go tohttp://example.com/website/bad
, we will be redirected to the same page, but with an error message. Refreshing the index page will hide the message.
How it works...
We are setting a flash message with Yii::app()->user->setFlash('success', 'Everything went fine!')
, for example, calling CWebUser::setFlash
. Internally, it is saving a message into a user state, so in the lowest level, our message is being kept in $_SESSION
until Yii::app()->user->getFlash('success')
is called and the $_SESSION
key is deleted.
There's more…
The following URL contains an API reference of CWebUser
and will help you to understand flash messages better:
- RAW攝影后期從入門到精通:Photoshop+Lightroom雙修精解
- Microsoft Forefront UAG 2010 Administrator's Handbook
- 中文版SolidWorks 2015技術大全
- Oracle SQL Developer 2.1
- SOLIDWORKS 2021中文版基礎入門一本通
- 光影之書:Photoshop+Camera Raw攝影后期與創意合成
- 3ds Max/MaxScript印象 腳本動畫制作基礎與應用
- SketchUp/Piranesi印象彩繪表現項目實踐
- Mastering phpMyAdmin 3.1 for Effective MySQL Management
- Building Websites with ExpressionEngine 1.6
- 3dsMax 2018動畫制作基礎教程(第4版)
- Learning Ext JS
- Photoshop CS6圖像處理立體化教程
- Photoshop CS6 中文版從入門到精通
- 中文版Photoshop CS6經典自學教程(培訓教材版)