Reputation: 33408
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?
Upvotes: 3
Views: 6758
Reputation: 33408
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).
Upvotes: 6
Reputation: 4522
Well, according to the api, the SessionHelper returns a string (with the flash message and element) when you do $this->Session->flash('location_key')
, so why not store that string into a variable?
$myFlash = $this->Session->flash('location_key');
if ($myFlash)
/*etc*/
echo $myFlash;
Upvotes: 1
Reputation: 66358
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')) {
...
}
Upvotes: 2