How to set flash in CAKEPHP view?

Asked

Viewed 306 times

1

In the method in my controller I select the flash, according to the condition.

if ($this->Auth->user()) {  
//redireciona apos o login;  

echo $this->Session->setFlash("Bem-vindo");  
} 

How can I display this directly from the view instead of in the method? For example, the method would return true in case of logged in and on the page to which I directed the user I would access the flash message or something like.

I don’t want to use echo, since it is a short and temporary message or until the page is reloaded or updated.

I tried to access the $this->Session->setFlash(), but gives helper error. Maybe, me creating a helper would solve the problem then? The $this->Session->flash() no message. I would only access a component, in case it could be the Auth, for example: $this->Session->flash('Auth');

Someone suggests something?

2 answers

2

I don’t know which version of Cakephp you’re using, but in 1.2 just use the $Session helper and call the flash() method without "echo"

<html>
<body>
<?php
if ($session -> check('Message.flash')) {
  $session -> flash();
}
?>
<div>sua pagina normal</div>
</body>

Link: http://api.cakephp.org/1.2/class-SessionHelper.html#_flash

0

Since you didn’t specify which version, I’m complementing the answer from Claytinho

In the version 2.x from Cakephp

// In the view.
echo $this->Session->flash();

In the version 3.x from Cakephp

// In your Controller
$this->Flash->success('The user has been saved', [
    'key' => 'positive',
    'params' => [
        'name' => $user->name,
        'email' => $user->email
    ]
]);

// In your View
<?= $this->Flash->render('positive') ?>

<!-- In src/Template/Element/Flash/success.ctp -->
<div id="flash-<?= h($key) ?>" class="message-info success">
    <?= h($message) ?>: <?= h($params['name']) ?>, <?= h($params['email']) ?>.
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.