Flash messages not being displayed

Controller:




if($model->save())

{

	Yii::app()->user->setFlash('success', "Your changes were saved successfully");

	$this->redirect(array('view'));

}



view.php:




<?php if(Yii::app()->user->hasFlash('success')):?>

	<div class="flash-success">

	<?php Yii::app()->user->getFlash('success'); ?>

	</div>

<?php endif; ?>



The div container is displayed but the message is not. I have inspected using Firebug and the message is definitely not there.

Anyone got any idea what the problem could be?

Yes. You need to echo your message such as:


<?php echo Yii::app()->user->getFlash('success'); ?>

Hope this helps

Thanks boss ;)

Any way to simplify this code:


<?php if(Yii::app()->user->hasFlash('success')):?>

	<div class="flash-success">

	<?php echo Yii::app()->user->getFlash('success'); ?>

	</div>

<?php endif; ?>

It just seems very long and untidy.

I would guess…design a separate class or static method to handle just Flash messages through attributes and the attribute being the Flash id…I would also be interested to hear what other people have invented in this direction.

One idea is to have a shortcuts functions (read this cookbook)

and add this function:




function printFlash($flash,$div_flash_class = 'flash-success'){

   if(Yii::app()->user->hasFlash('success')){

  	echo '<div class="'.$div_flash_class.'">';

   echo Yii::app()->user->getFlash('success');

  	echo '</div>';

   }

}




And use it




printFlash('success'); //in your case, nothe that you can pass the class to aply to the div too...



Excellent idea PoL. Thanks

How about putting the code in another view file and then displaying it using renderPartial()?

Is not a bad Idea, in fact is the same principle: reusability.

I do this:


<?php $this->widget('FlashMessageWidget'); ?>

And in order to set:


Yii::app()->user->setErrorFlash()

Yii::app()->user->setNoticeFlash()

Yii::app()->user->setSuccessFlash()

Have you extended CWebUser? Can you elaborate a bit further on your implementation. It looks very interesting

Yes extended with a subclass. Like:




public function setErrorFlash($title, $message)

{

   $this->setFlash('error', array('title' => $title, 'message' => $message));

}



Note that the second argument of CWebUser::setFlash() can be anything.