Pamąstymai apie programavimą, dizainą ir gyvenimą

"Only the dead have seen the end of the war" - Plato

Pamąstymai apie programavimą, dizainą ir gyvenimą header image 2

Discover layouts for setFlash method in CakePHP

August 27, 2008 · komentarų 0

Few years ago I needed to show users visually different messages that would work similarly as $this->Session->setFlash() works and I’ve developed custom component to accomplish this task. If you have similar needs, then you don’t have to develop anything, because Cake has an answer for you!

It appears that setFlash method of the Session component has few aces up it’s sleeve. Probably not many of us have read the API description for this method. It takes 4 parameters: messages, layout, params and key. For what I’m going to show you, first 2 parameters are enough, though the third parameter might be really useful depending on your app’s logic.

Let me show you how this helps to produce nice visual response to the user. Lets create /app/layouts/messages/success.ctp

<div class="success_message">
<?php echo $content_for_layout; ?>
</div>

and then /app/layouts/messages/failure.ctp

<div class="failure_message">
<?php echo $content_for_layout; ?>
</div>

To show user some pretty messages in the controller you just use:

$this->Session->setFlash('You have created your first nightmare', 'messages/success');
// or
$this->Session->setFlash('You have failed miserably, all your base are belong to us', 'messages/failure');

And you need to show the flash somewhere in your layout:

<?php if ($session->check('Message.flash'))
{
    $session->flash();
}
?>

Let’s make those messages visually different by defining styles:

.success_message
{
    background: #ccffcc;
    border: solid 1px #66cc33;
    padding: 8px;
    color: #000;
    font-weight: bold;
}

.failure_message
{
    background: #ffcccc;
    border: solid 1px #cc3333;
    padding: 8px;
    color: #000;
    font-weight: bold;
}

And here’s the result for you to see:

That makes it easy to add some JS effects or other eye candy to the messages that users see.

komentarų 0 Žymės:·