Skip to content

Flash messages

Mark Sch edited this page Oct 16, 2016 · 11 revisions

Using the Common component's flashMessage() you can have colorful (success, warning, error, ...) flash messages. They also can stack up (multiple messages per type). This way no message is lost when redirecting twice etc.

DEPRECATED

Use Flash plugin.

Demo

sandbox/examples/messages

Flash messages

Both Common Component and the Common Helper are added in the AppController:

public $components = array(..., 'Tools.Flash');
public $helpers = array(..., 'Tools.Flash');
// Using Tools.Flash component
$this->Flash->message('Yeah', 'success');
$this->Flash->message('Yeah again!', 'success');
$this->Flash->message('A Warning in yellow', 'warning');
$this->Flash->message('An Error in red', 'error');
$this->Flash->message('Just some white info box text', 'info');

Or use the shortcut:

$this->Flash->success('Yeah');
// etc

Use this instead of the default code in your layout ctps:

// Using Tools.Flash helper
echo $this->Flash->flash();

And don't forget to style your flash messages, e.g.: cakephp-sandbox/blob/master/webroot/css/flash_messages.css

Transient flash messages

You can also put flash messages on top that are not stored in session but Configure (for this request only). This can be useful if you don't intend to redirect and don't want them to show up if that happens.

// Using Common component
$this->Flash->transientMessage('A Success message', 'success');
// etc

You can also add those in the view layer if needed (prior to the output, of course):

// Using Common helper
$this->Flash->addMessage('A Success message', 'success');

Output in a specific order or only specific types

You can filter the output, both in order and types:

// Using Common helper
echo $this->Flash->render(array('warning', 'error'));

In this case it would only output the warning and error messages, in this order (Usually the order is "error, warning, success, info").

References

http://www.dereuromark.de/2014/04/21/cakephp-flash-messages-2-0/