Mike Rockétt
Mike Rockétt

Reputation: 9007

Silex: Redirect with Flash Data

I need to redirect one page to another with a message in Silex. Hopefully there's a Laravelesque way of doing it, but I highly doubt it:

$app->redirect('/here', 301)->with('message', 'text');

I'd then want to display the message in my template:

{{ message }}

If not, is there another way?

Update

I see there's a getFlashBag method in Symfony - is that what I'm supposed to use? Specifically, I am using the Bolt Content Management system.

Upvotes: 14

Views: 7676

Answers (2)

mpen
mpen

Reputation: 282895

I created this simple FlashBagTrait that may be of use:

<?php
use 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"));

Upvotes: 5

a4c8b
a4c8b

Reputation: 925

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

Upvotes: 32

Related Questions