开发者

How to overdrive FLASH MESSAGE default of 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->setF开发者_如何学运维lash('this is message')? How do I modify the standard layout? I don't want to modify it with css or javascript.


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


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>';


According to CakePHP book entry on flash():

<?= $session->flash(); ?>

in a view file outputs:

<div id='flashMessage' class='message'>My Message</div>

So there is nothing to override but the CSS for this id in cake.generic.css.

Hope I understood the question correctly. =)


You cannot override default HTML for a flash message. What I did is: created the following function in app_controller:

protected function _f($message, $url=false) {
    $this->Session->setFlash($message,'message');
    if($url) $this->redirect($url);
}

Created my own message.ctp template in views/elements.

Then used the _f function inc all controllers like this:

$this->_f('This is a flash message','/page_to_redirect/');


Have you tried to create a default.ctp in elements folder?

That might be what you wanted?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜