Nick Tsarev
Nick Tsarev

Reputation: 103

Symfony 2.1 app.session.flashbag.get('something') returns empty value

I have a trouble with using app.session.flashbag.get('notice').

In the controller I make

public function updateAction(Request $request, $id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('SomeBundle:SomeEntity')->find($id);

    $editForm = $this->createForm(new SomeEntityType(), $entity);
    $editForm->bind($request);

    if ($editForm->isValid()) {
        $em->persist($entity);
        $em->flush();

        $flash = $this->get('translator')->trans('Some Entity was successfully updated');
        $this->get('session')->getFlashBag()->add('notice', $flash);

        return $this->redirect($this->generateUrl('some_entity_edit', array('id' => $id)));

    }

In editAction I'm getting information from the session:

public function editAction($id)
{
    $em = $this->getDoctrine()->getManager();

    $flashes = $this->get('session')->getFlashBag()->get('notice', array());

    //...
    //...

    return array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'flashes' => $flashes
    );
}

And i'm trying in the TWIG get information from the session :

TWIG: {% for flashMessage in app.session.flashbag.get('notice') %}{{ flashMessage }}{% endfor %}

PHP: {% for flashMessage2 in flashes %}{{ flashMessage2 }}{% endfor %}

The app.session.flashbag.get('notice') is empty, the flashes has a value.

Do you have any ideas, why I can't get data from the app.session.flashbag.get('notice')?

Upvotes: 1

Views: 10677

Answers (2)

DeadManSpirit
DeadManSpirit

Reputation: 2096

There is an easy way to handle (add/display) Symfony flash messages with FlashAlertBundle, it is standalone Symfony2 bundle implemented with pure JavaScript, so you don't have to worry about using JS libraries.

You just need the following code to render flash messages on your twig template:

{{ render_flash_alerts() }}

Available through
https://github.com/rasanga/FlashAlertBundle
https://packagist.org/packages/ras/flash-alert-bundle

Upvotes: 0

l3l0
l3l0

Reputation: 3393

Its normal behavior. You access flash in controller first, so it is returned and unset then. When you access it again then key does not exists in flashbag that way is empty.

See FlashBag::get at github

Upvotes: 5

Related Questions