- Yii Application Development Cookbook(Second Edition)
- Alexander Makarov
- 268字
- 2021-11-12 16:36:14
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 well 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 do we pass it from the current page to the redirect target and clean up 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 theindex
page will hide the message.
How it works...
We set a flash message with Yii::app()->user->setFlash('success', 'Everything went fine!')
, for example, calling CWebUser::setFlash
. Internally, it saves a message into a user state, so at 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:
- Getting Started with WebRTC
- 企業(yè)私有云建設(shè)指南
- Practical Web Design
- 世界互聯(lián)網(wǎng)發(fā)展報告·2019
- Getting Started with Grunt:The JavaScript Task Runner
- 網(wǎng)絡(luò)基礎(chǔ)與網(wǎng)絡(luò)管理項目化教程
- Scala Design Patterns.
- 互聯(lián)網(wǎng)+思維與創(chuàng)新:通往未來的+號
- 深入理解OpenStack Neutron
- Implementing NetScaler VPX?
- 物聯(lián)網(wǎng),So Easy!
- 移動互聯(lián)網(wǎng)環(huán)境下的核心網(wǎng)剖析及演進
- 算力網(wǎng)絡(luò):云網(wǎng)融合2.0時代的網(wǎng)絡(luò)架構(gòu)與關(guān)鍵技術(shù)
- 趣話通信:6G的前世、今生和未來
- Hands-On Cloud:Native Microservices with Jakarta EE