官术网_书友最值得收藏!

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...

  1. 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');
       }
    }
  2. 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?>
  3. Now, if we go to http://example.com/website/ok, we'll be redirected to http://example.com/website/index and a success message will be displayed. Moreover, if we go to http://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:

http://www.yiiframework.com/doc/api/CWebUser

主站蜘蛛池模板: 安丘市| 安塞县| 江华| 永兴县| 策勒县| 当涂县| 福安市| 巫溪县| 西乌珠穆沁旗| 九龙城区| 东山县| 年辖:市辖区| 清新县| 疏勒县| 安泽县| 吕梁市| 诏安县| 桂阳县| 开封县| 尚志市| 建阳市| 安乡县| 保靖县| 兴文县| 龙川县| 宁陵县| 宁陵县| 兰溪市| 鄂托克前旗| 嘉荫县| 乌鲁木齐县| 辽宁省| 湟源县| 方城县| 饶阳县| 建水县| 南木林县| 岑巩县| 贵溪市| 维西| 通许县|