cv0ctq
Last Updated: February 25, 2016
·
5.292K
· zoltanradics
360

Silex - How to use Flash messages

First of all, you have to register SessionServiceProvider:

/**
  Session setup
**/
$app->register(new Silex\Provider\SessionServiceProvider());

Now you can define Flash message in your controller method, which will shown up right after the redirection:

$app->get('/whatever', function() use($app) { 
  # Set flash message and return redirect
  $app['session']->getFlashBag()->add('example', 'Some example flash message');
  return $app->redirect('redirect-to-some-route');
});

This is how you can catch the Flash message in your template file:

{% for alert in app.session.flashbag.get('example') %}
<div class="error-message">
  <div class="alert"><strong>{{ alert }}</strong></div>
</div>
{% endfor %}
Say Thanks
Respond

2 Responses
Add your response

15335
3e9975d51319d5011a00b9c826373a17

Twig code will throw error, there's a typo, looping for alerts and trying to print example.

over 1 year ago ·
21806
D5znqydv normal

That is not an optimal solution. It will create a session cookie for every request. You should use peekAll first. See this gist: https://gist.github.com/Nyholm/4c2a960531d5d81c062b

over 1 year ago ·