Wednesday, September 4, 2013

My awesome flash system

Hi,

This is first time I am working with cakephp and I was not satisfied with the flash message system in cakephp.

Here is how to setup your own awesome flash system (MIT License) :

- Multiple messages for each type
- Separate divs for each type
- Each message shown as <li>

Create a file : app/View/Helper/FlashExtHelper.php

<?php
// MIT License
App::uses('AppHelper', 'View/Helper');
App::uses('CakeSession', 'Model/Datasource');

class FlashExtHelper extends AppHelper {

    public function flashExt() {
        $out = false;

        if (CakeSession::check('FlashExt')) {
            $messages = (array)CakeSession::read('FlashExt');
            foreach($messages as $key => $type) {
                $out .= '<div id="flash" class="' . $key . '\">';
                $out .= '<ul>';
                foreach ($type as $key => $message) {
                    $out .= '<li>' . $message . '</li>';
                }
                $out .= '</ul>';
                $out .= '</div>';
            }
            CakeSession::delete('FlashExt');
        }

        return $out;
    }
}
?>

Add the following in app/Controller/AppController.php :

class AppController extends Controller {
    public $helpers = array('FlashExt');

    // MIT License
    function setFlashExt($message, $type) {
        $messages = (array)$this->Session->read('FlashExt');
        $messages[$type][] = $message;
        $this->Session->write('FlashExt', $messages);
    }
}

Use it in your views :

<?php echo $this->FlashExt->flashExt(); ?>

Use it in your controllers :

$this->setFlashExt('message', 'notice');
$this->setFlashExt('message', 'success');
$this->setFlashExt('message', 'error');

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
 
---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/groups/opt_out.

No comments: