Last Updated: February 25, 2016
· zoltanradics

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>
{% endfor %}

2 Responses
Add your response


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

over 1 year ago ·

That is not an optimal solution. It will create a session cookie for every request. You should use peekAll first. See this gist:

over 1 year ago ·