Flash messages and redirect

Yii’s flash messages disappear any time I use an HTTP redirect. This is easy to reproduce; just add some flash messages to the actionCreate() or actionUpdate() methods generated by the Gii CRUD generator. It seems that the lifetime of 1 request is too short. Here’s an example:

In, e.g., ProductController::actionInsert(), I put:




if ($model->save()) {

	Yii::app()->user->setFlash('success', 'Product was created successfully.');

	$this->redirect(array('view','id'=>$model->id));

}



Then I try to display the flash messages at the top of the next page with a partial view like:




<?php

if ($messages = Yii::app()->user->getFlashes()) {

	unset($messages['counters']);

	foreach ($messages as $key=>$msg) {

		$message_type = 'information';

		if (substr($key,0,7) == 'success') $message_type = 'success';

		if (substr($key,0,7) == 'warning') $message_type = 'warning';

		if (substr($key,0,5) == 'error') $message_type = 'error';

	?>

<div class="flash-<?php echo $message_type; ?>">

	<?php echo $msg; ?>

</div>

	<?php

	}

} ?>



But the messages aren’t there. Here’s what appears to be happening:

  1. My code sets a flash message (typically in the controller, sometimes the model)

  2. At some point (during the current request? I’m not sure), the flash message’s counter gets incremented

  3. CController::redirect() is called which redirects the browser (ending the current request and starting a new one)

  4. At the beginning of the new (post-redirect) request, CWebUser::updateFlashes() sees that the flash message’s counter is > 0 and deletes it

  5. The flash message display view is renderPartial()ed but doesn’t find any flash messages, because they were deleted in step 4

If I remove the redirect in the controller, and render a view instead, I can see the flash messages. Then if I put the redirect back in, the flash messages disappear again.

Am I doing something wrong here? Is there a different logic I should be using with my redirects? On a different thread, someone mentioned that this can happen if there is AJAX validation going on, but I have that turned off (to the best of my knowledge).

I had to override CWebUser::getFlash() and CWebUser::updateFlash() to eliminate the counter logic, so the messages would stay in the session until they were displayed.

Yii 1.1.7 apparently includes a property CWebUser::autoUpdateFlash which can be set to false to turn off the flash message counter. Messages will then stay in the session until they’re displayed. But why is the counter getting incremented that extra time in the first place?

I’m experiencing this same problem with dissapearing flash variables after a redirect.

Flash messages and redirect