- 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:
- 現代企業應用設計指南
- MATLAB計算機視覺經典應用
- AutoCAD 2020中文版從入門到精通(標準版)
- Adobe創意大學Illustrator產品專家認證標準教材(CS6修訂版)
- 中文版Photoshop CS6平面設計實例教程(第2版)
- Photoshop CC摳圖+修圖+調色+合成+特效實戰視頻教程
- Premiere Pro CC 2018基礎教程(第3版)
- Designing and Implementing Linux Firewalls and QoS using netfilter, iproute2, NAT and l7/filter
- iPad Procreate風格繪畫之美
- 中文版Photoshop平面設計入門教程
- SketchUP草圖繪制從新手到高手
- Photoshop攝影后期必修5項核心技法 基本調整+光影校正+色彩修飾+局部處理+銳化降噪
- Photoshop CC 2015中文版實用教程(第7版)
- After Effects影視特效與電視欄目包裝實例精粹
- CorelDRA WX8中文版從入門到精通