Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP: Check if SPECIFIC flash message is set

I have a page with several sections with forms that are submitted from the same page. The forms collapse to save space, but I want to conditionally keep them open if there is an error on submission.

In my controller, I set a specific "key" (see location_key below) for each form, which allows me to echo them in their respective locations:

In controller:

$this->Session->setFlash('You missed something...', 'element_name', array('class'=>'error'), 'location_key');

In view:

$this->Session->flash('location_key')

I'm trying to figure out how to check if $this->Session->flash('location_key') exists. If I do this it works but unsets the flash message:

if ( $this->Session->flash('location_key') ) // = TRUE
    //Do something
$this->Session->flash('location_key') // = FALSE (because it just got called)

How can I test for the presence of this flash message without causing it to go away?

like image 548
emersonthis Avatar asked Mar 29 '26 23:03

emersonthis


2 Answers

Figured it out! This works:

$this->Session->check('Message.location_key')

It returns true/false depending on whether there are any such flash messages set. ->read() does the same thing, but returns the flash data if there is (any and crucially, it leaves the session var so it can still be echoed later).

like image 107
emersonthis Avatar answered Apr 02 '26 03:04

emersonthis


Flash messages are (surprise) stored in the session:

public function setFlash($message, $element = 'default', $params = array(), $key = 'flash') {
    CakeSession::write('Message.' . $key, compact('message', 'element', 'params'));
}

To test for the presence of a flash message, test for the equivalent key in the session, e.g.:

if (CakeSession::check('Message.location_key')) {
    ...
}
like image 20
AD7six Avatar answered Apr 02 '26 02:04

AD7six



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!