Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 - add flashbag message on entity operations

I'm working on a Symfony2.3.6 project, and it works good. I've made a backend side with a few CRUD for some Entities, and it also work good.

Now what I want to do is notify an user when an operation is made on an entity. So I want to notify when an entity is saved, updated or deleted, as Symfony1.4 made. I was in doubt where to put the flashbag message, if in the entity or in the controller or even with events?!

Which is the right place where I can put this kind of feature, and how I can do it? Thanks...

like image 755
ilSavo Avatar asked Nov 18 '25 20:11

ilSavo


1 Answers

The documentation describes perfectly how to store and display these messages in your controller.

In your controller

public function updateAction(Request $request)
{
    $form = $this->createForm(...);

    $form->handleRequest($request);

    if ($form->isValid()) {
        // do some sort of processing

        $this->get('session')->getFlashBag()->add(
            'notice',
            'Your changes were saved!'
        );

        return $this->redirect($this->generateUrl(...));
    }

    return $this->render(...);
}

In your Twig template

% for flashMessage in app.session.flashbag.get('notice') %}
    <div class="flash-notice">
        {{ flashMessage }}
    </div>
{% endfor %}

You can use different flashbags for other messages, for example an error :

In your controller

[...]
        $this->get('session')->getFlashBag()->add(
            'delete',
            'The entity has been deleted!'
        );
[...]

In your Twig template

% for flashMessage in app.session.flashbag.get('delete') %}
    <div class="flash-notice delete">
        {{ flashMessage }}
    </div>
{% endfor %}

Use CSS to style the delete class.

like image 151
A.L Avatar answered Nov 22 '25 05:11

A.L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!