Difference between #2 and #3 of
An easy way to display a success page using flash messages

Revision #3 has been created by qiang on Apr 12, 2011, 1:06:08 AM with the memo:

Added "refactoring the code" section
« previous (#2) next (#4) »


Title unchanged

An easy way to display a success page using flash messages

Category unchanged


Yii version unchanged

Tags unchanged

flash message, Forms

Content changed

So what are new stuff here?

* First, instead of saving a string as flash message, we save an array of data that will persist to the next page request.

* Second, we use the action code to control which view to render. The code conforms better to the MVC pattern.

## Refactoring the code
If an application needs to display different success pages in different actions, we may refactor the above code so that the usage is even simpler and more DRY.
First in the [base controller class](http://www.yiiframework.com/wiki/121/extending-common-classes-to-allow-better-customization), define the following method:
 * Renders a success view.
 * Note that this method will redirect the browser to the 'site/success' route
 * which will then render the specified success view.
 * @param string $view the view name. It can be a view relative to
 * the current controller or an absolute view (starting with '/')
 * @param array $data the data to be passed to the view.
public function success($view, $data=array())
if($view[0]!=='/')  // relative to current controller
$view = '/' . $this->id . '/' . $view;
$data['_view_'] = $view;
Yii::app()->user->setFlash('_success_', $data);
Then, in the `SiteController` class, define the following `success` action:
 * Displays a success page.
 * The success page content is specified via the flash data '_success_'
 * which is generated by {@link Controller::success()} method.
 * If the flash data does not exist, it will redirect the browser to the homepage.
public function actionSuccess()
if (!Yii::app()->user->hasFlash('_success_'))
$data = Yii::app()->user->getFlash('_success_');
$view = $data['_view_'];
$this->render($view, $data);
Now, the previous `actionRegister()` method can be greatly simplified:
public function actionRegister()
$model = new User('register');
if (isset($_POST['User']))
$model->attributes = $_POST['User'];
if ($model->save())
$this->success('registerSuccess', array(
'username' => $model->username,
'email' => $model->email,
$this->render('register', array('model'=>$model));
And we can call the `success()` method in any other action as long as it needs to display a success page.
21 0
Viewed: 43 308 times
Version: 1.1
Category: Tips
Written by: qiang
Last updated by: qiang
Created on: Apr 11, 2011
Last updated: 7 years ago
Update Article


View all history