Buy

Save, Redirect, setFlash (and Dance)

We already have the finished Genus object. So what do we do now? Whatever we want!

Probably... we want to save this to the database. Add $genus = $form->getData(). Get the entity manager with $em = this->getDoctrine()->getManager(). Then, the classic $em->persist($genus) and $em->flush():

52 lines src/AppBundle/Controller/Admin/GenusAdminController.php
... lines 1 - 12
class GenusAdminController extends Controller
{
... lines 15 - 31
public function newAction(Request $request)
{
... lines 34 - 37
if ($form->isSubmitted() && $form->isValid()) {
$genus = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($genus);
$em->flush();
... lines 44 - 45
}
... lines 47 - 50
}
}

Always Redirect!

Next, we always redirect after a successful form submit - ya know, to make sure that the user can't just refresh and re-post that data. That'd be lame.

To do that, return $this->redirectToRoute(). Hmm, generate a URL to the admin_genus_list route - that's the main admin page I created before the course:

52 lines src/AppBundle/Controller/Admin/GenusAdminController.php
... lines 1 - 12
class GenusAdminController extends Controller
{
... lines 15 - 31
public function newAction(Request $request)
{
... lines 34 - 37
if ($form->isSubmitted() && $form->isValid()) {
... lines 39 - 44
return $this->redirectToRoute('admin_genus_list');
}
... lines 47 - 50
}
}

Because redirectToRoute() returns a RedirectResponse, we're done!

Time to try it out. I'll be lazy and refresh the POST. We should get a brand new "Sea Monster" genus. There it is! Awesome!

Adding a Super Friendly (Flash) Message

Now, it worked... but it lack some spirit! There was no "Success! You're amazing! You created a new genus!" message.

And I want to build a friendly site, so let's add that message. Back in newAction(), add some code right before the redirect: $this->addFlash('success') - you'll see where that key is used in a minute - then Genus created - you are amazing!:

54 lines src/AppBundle/Controller/Admin/GenusAdminController.php
... lines 1 - 12
class GenusAdminController extends Controller
{
... lines 15 - 31
public function newAction(Request $request)
{
... lines 34 - 37
if ($form->isSubmitted() && $form->isValid()) {
... lines 39 - 44
$this->addFlash('success', 'Genus created!');
return $this->redirectToRoute('admin_genus_list');
}
... lines 49 - 52
}
}

It's good to encourage users.

But let's be curious and see what this does behind the scenes. Hold command and click into the addFlash() method:

398 lines vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php
... lines 1 - 38
abstract class Controller implements ContainerAwareInterface
{
... lines 41 - 102
/**
* Adds a flash message to the current session for type.
*
* @param string $type The type
* @param string $message The message
*
* @throws \LogicException
*/
protected function addFlash($type, $message)
{
if (!$this->container->has('session')) {
throw new \LogicException('You can not use the addFlash method if sessions are disabled.');
}
$this->container->get('session')->getFlashBag()->add($type, $message);
}
... lines 119 - 396
}

Okay, cool: it uses the session service, fetches something called a "flash bag" and adds our message to it. So the flash bag is a special part of this session where you can store messages that will automatically disappear after one redirect. If we store a message here and then redirect, on the next page, we can read those messages from the flash bag, and print them on the page. And because the message automatically disappears after one redirect, we won't accidentally show it to the user more than once.

And actually, it's even a little bit cooler than that. A message will actually stay in the flash bag until you ask for it. Then it's removed. This is good because if you - for some reason - redirect twice before rendering the message, no problem! It'll stay in there and wait for you.

Rendering the Flash Message

All we need to do now is render the flash message. And the best place for this is in your base template. Because then, you can set a flash message, redirect to any other page, and it'll always show up.

Right above the body block, add for msg in app.session - the shortcut to get the session service - .flashbag.get() and then the success key. Add the endfor:

49 lines app/Resources/views/base.html.twig
<!DOCTYPE html>
<html>
... lines 3 - 13
<body>
... lines 15 - 28
<div class="main-content">
{% for msg in app.session.flashBag.get('success') %}
... lines 31 - 33
{% endfor %}
... lines 35 - 36
</div>
... lines 38 - 46
</body>
</html>

Why success? Because that's what we used in the controller - but this string is arbitrary:

54 lines src/AppBundle/Controller/Admin/GenusAdminController.php
... lines 1 - 12
class GenusAdminController extends Controller
{
... lines 15 - 31
public function newAction(Request $request)
{
... lines 34 - 37
if ($form->isSubmitted() && $form->isValid()) {
... lines 39 - 44
$this->addFlash('success', 'Genus created!');
... lines 46 - 47
}
... lines 49 - 52
}
}

Usually I have one for success that I style green and happy, and on called error that style to be red and scary.

I'll make this happy with the alert-success from bootstrap and then render msg:

49 lines app/Resources/views/base.html.twig
<!DOCTYPE html>
<html>
... lines 3 - 13
<body>
... lines 15 - 28
<div class="main-content">
{% for msg in app.session.flashBag.get('success') %}
<div class="alert alert-success">
{{ msg }}
</div>
{% endfor %}
... lines 35 - 36
</div>
... lines 38 - 46
</body>
</html>

Cool! Go back and create Sea Monster2. Change its subfamily, give it a species count and save that sea creature! Ocean conservation has never been so easy.

And, I'm feeling the warm and fuzzy from our message.

Next, let's really start to control how the fields are rendered.

Leave a comment!

  • 2017-11-15 Victor Bocharsky

    Hey Peter,

    We don't have any plans to make a separate tutorial about form events, but we do have a few related screencasts that explain this concept, check it out:
    - https://knpuniversity.com/s...
    - https://knpuniversity.com/s...

    But if you stuck on some step with it, we'd be glad to help you.

    Cheers!

  • 2017-11-15 Peter Kosak

    Is there any plan to create tutorial for dynamically generating form based on user data. I found documentation but real struggle is when form is invalid to keep submited values and filtered options.

    Basically example of each of these: https://symfony.com/doc/cur...

  • 2017-08-17 Mike

    It makes me feel better, because I know I haven't overseen anything! Many thanks for your AWESOME LIGHNING FAST comments / help, iam really feeling more dangerous and have just started 2 weeks ago. You're awesome!

  • 2017-08-15 weaverryan

    Yo Mike!

    Hmm, interesting. So, in general, auto-completion in Twig is not rock solid. Usually, it's because you're using some variable in a template... and since PhpStorm doesn't 100% know which controller is rendering that template (it tries to guess), sometimes it may not auto-complete. And even when it does know what variables are available, it doesn't always know what *type* those variables are (this goes back to adding good @return statements, etc).

    But your situation is more mysterious... which is never a good thing ;). I can see that when it's auto-completing the global App variable, it *knows* that this is an AppVariable object! And so therefore, it should be smart enough to know that any get* methods on that class (e.g. getSession) can be accessed via the app.session key. And actually, I just tested with the latest versions of everything, and I also don't get this auto-completion :/. It seems like it's some bug in storm or the plugin. I don't know if that will make you feel better or worse ;). Hopefully it will resolve itself.

    Cheers!

  • 2017-08-14 Mike

    Even after a click on "clear index" and wait until it is completed, the same behavior. app.$x doesn't autocomplete. (Well it does kind of but not the way it should be, see the pictures: http://imgur.com/a/LPrMV )

    Its strange because things like error.$x does get autocompleted.
    Iam on macOS 10.12.6.

  • 2017-08-14 Diego Aguiar

    Hmm, look's like your configuration is correct
    Try clearing index in symfony plugin details and exclude from your project "var/cache" folder
    Are you on Windows ?

  • 2017-08-12 Mike

    Hey Diego, I've reviewed everything and even deleted the cache of the project, doesn't seem to work.

    Here are all infos for you:

    Repository from me:

    https://github.com/emovere/...

    Pictures of PHPStorm Settings you requested:

    http://imgur.com/a/LPrMV

    I really hope you can help to get the autocomplete working for TWIG app.

    I assist you with everything you need.

  • 2017-08-10 Diego Aguiar

    Hey Mike

    Which version oh PHPStorm are you using ? You might need to upgrade it, aswell the Symfony plugin
    Have you checked your settings for the Symfony plugin ? settings->language&frameworks->symfony - make sure all the checkboxes related to twig are checked

    Cheers!

  • 2017-08-10 Mike

    One more note:
    In the video, "app" gets autocompleted by Symfony\Bundle\FrameworkBundle\Templa.. but in my case app gets autcompleted by \Symfony\Bridge\Twig\AppVariables

    And of course Ive installed the symfony plugin, on every video before this one autocompletion worked as expected

  • 2017-08-10 Mike

    Everything works and is AMAZING! But I don't get autocompletion in the for loop at twig.

    if I type "app". <- "app" will be autocompleted
    but everything after app. nothing is shown, I get the "no suggestion" message

    Do you know why this could be happening?
    In the video every option of app.session.flashBag.get('success') could be autocompleted.

  • 2017-07-19 Diego Aguiar

    haha, it have happened to me too (Symfony punching your brain while sleeping) :)

  • 2017-07-19 Juan Nicolás

    Thanks for answer me Diego (at two questions :) I did can't sleep thinking about Symfony. Too much to learn.

    Have a nice day!

  • 2017-07-19 Diego Aguiar

    Hey Juan Nicolás

    In that case you can pass them as *query* parameters of the URL (e.g. site.com/your/route?number1...
    If that doesn't work as you want, there are other options, like saving it in the filesystem or in the Session, just like the flash message

    I hope it helps you :)

    Cheers!

  • 2017-07-18 Juan Nicolás

    Hello,
    And if I don't want to save the data into my DB, how can I pass the data into another controller?

    For example, I have "number1 = 1" and "number2 = 2", on my next controller I need to sum them and show the result. Nothing with a DB.

    What is the correct process to do something like that? Thanks again.

  • 2017-02-14 Blueblazer172

    Yeah that works :) Thanks

  • 2017-02-14 Victor Bocharsky

    Hey Blueblazer172 ,

    Where do you call your addFlash() method? It should be right before redirect to the other page, then when you successfully save your entity - you will be redirected to the other page and then reloading page do nothing.

    Cheers!

  • 2017-02-14 Blueblazer172

    when i refresh the page on the /new page it shows up my message twice. Why is that so?
    can i prevent that ?

  • 2016-12-22 the_nuts

    Thank you!

  • 2016-12-22 Victor Bocharsky

    Hey the_nuts,

    Actually, it depends. If you pass $genus object to the createForm() as a second argument - then you don't need to call $genus = $form->getData():


    $genus = new Genus;
    $form = $this->createForm(GenusFormType::class, $genus);
    // the $genus object will be updated after handleRequest() call

    Cheers!

  • 2016-12-22 the_nuts

    Is the $genus = $form->getData() needed?
    I see no difference in using it or no, the object is updated by handleRequest

  • 2016-11-14 Terry Caliendo

    Got it. Thanks.

  • 2016-11-13 weaverryan

    Very astute Terry! That's exactly it: each "key" in the flash bag is actually an array that can hold many values. Most of the time, you don't need this, but it's built with that flexibility. The only time I've ever relied on this is a few times when I've used the flash bag to send custom analytic information. When the user takes an action, I would record it in a special place on the flashbag. Then, the next time a full HTML page was loaded, we would read those flash messages and render some custom JS to send that info to the analytics service. In this case, it was possible that the user would take *multiple* actions, before the next full page load... and that was totally fine :).

    Cheers!

  • 2016-11-12 Terry Caliendo

    Towards the end you you do a for loop on the flashbag in twig on the "success". Does this mean you can have multiple calls in your controller to submit to the same "success" key without overwriting the last?