Silex: Redirect with Flash Data
Yes, FlashBag is the right way.Set a flash message in your controller (you can add multiple messages):
$app['session']->getFlashBag()->add('message', 'text');$app->redirect('/here', 301)
And print it in the template:
{% for message in app.session.getFlashBag.get('message') %} {{ message }}{% endfor %}
I created this simple FlashBagTrait
that may be of use:
<?phpuse Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;trait FlashBagTrait{ /** * @return FlashBagInterface */ public function getFlashBag() { return $this['session']->getFlashBag(); }}
Just add it to your Application
class and it will make things ever-so-slightly easier!
$app->getFlashBag()->add('message',array('type'=>"danger",'content'=>"You shouldn't be here"));{% if app.flashbag.peek('message') %}<div class="row"> {% for flash in app.flashbag.get('message') %} <div class="bs-callout bs-callout-{{ flash.type }}"> <p>{{ flash.content }}</p> </div> {% endfor %}</div>{% endif %}
Its main advantage is that type-hinting will work in PhpStorm.
You can also add it as a service provider,
$app['flashbag'] = $app->share(function (Application $app) { return $app['session']->getFlashBag();});
Which makes it more convenient to use from PHP (but you lose the type-hinting):
$app['flashbag']->add('message',array('type'=>"danger",'content'=>"You shouldn't be here"));