Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overdrive FLASH MESSAGE default of cakePHP

Tags:

cakephp

For $this->Session->setFlash('this is message','flash_error'); you only need to create flash_error.ctp in the elements folder to have a different look.

But what is with $this->Session->setFlash('this is message')? How do I modify the standard layout? I don't want to modify it with css or javascript.

like image 330
meotimdihia Avatar asked Dec 07 '22 01:12

meotimdihia


2 Answers

Laheab answer is right. But you can override it using the AppController beforeRender function. In your app/app_controller.php write this function :

function beforeRender(){
    if ($this->Session->check('Message.flash')) {
        $flash = $this->Session->read('Message.flash');

        if ($flash['element'] == 'default') {
            $flash['element'] = 'flash_error';
            $this->Session->write('Message.flash', $flash);
        }
    }
}

It will override the 'default' flash element with 'flash_error'. Then in app/views/elements create flash_error.ctp

like image 143
Jamal Aziz Avatar answered Jan 11 '23 18:01

Jamal Aziz


The HTML for flash messages is output in the flash method of the SessionHelper class. I find the easiest way to achieve what you're trying to do is to override the core SessionHelper class. To do this

Copy lib/Cake/View/Helper/SessionHelper.php to app/View/Helper/SessionHelper.php

Cake will now use the SessionHelper class in your app as opposed to it's own. Now you can update the flash method to output the HTML you want. On line 136, you'll see this:

$out = '<div id="' . $key . 'Message" class="' . $class . '">' . $message . '</div>';

As an example, if I'm using Twitter Bootstrap, I'll update this line to be:

$out = '<div class="alert fade in"><a class="close" data-dismiss="alert" href="#">&times;</a>' . $message . '</div>';
like image 38
Robert Love Avatar answered Jan 11 '23 18:01

Robert Love