Symfony & Sonata Admin

Add flash messages with parameters (Symfony 3.x / 4.x / 5.x)

Add flash messages with parameters using Symfony, a powerful framework!

However, sometimes it does not cover all my needs. On of the problem that I encountered was: “I want to set a flash (session) message in my controller, but I want this message to be translatable and this should have some parameters too”. How should I do it?

Further, I’ll explain how I covered this problem, but I’ll not dive into all Symfony structures and classes.

Symfony offers you a shortcut for this feature by ControllerTrait which implements addFlash(string $type, string $message) method and more (see documentation).

Otherwise, you can do this by injecting SessionInterface, calling getFlashBag() method and adding a new flash session message (see documentation).

Well, in this case I had two possibilities

I.Inject TranslatorInterface in my method(s), translate my text, then replace placeholders with my parameters:

<?php declare(strict_types = 1);

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class PlayerController extends AbstractController {
    public function createAccount(Request $request, EntityManagerInterface $em) {
        // ...
        // Some irrelevant code before
        $message = $translator->trans('Congratulations %username%! You account has been created!');
        $message = sprintf($message, $username);
        $this->addFlash('success', $message);
        return $this->redirectToRoute('create_account');
        // Another irrelevant code like rendering template
    }
}

This code works, but I have to call my translator every time before loading my flash session. For a small project, I can stick with that.

But as we know (or should know), Symfony uses Twig to render templates. Twig has an awesome function called trans which translates given text.

So here’s the other possibility and what I have chose.

II. Custom method to add flash sessions with parameters and custom way to render it!

Here’s what I did:

a) I created a custom AbstractController which extends Symfony’s base Controller

<?php declare(strict_types = 1);

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

/**
 * Class AbstractController
 * @package App\Controller
 */
abstract class AbstractController extends Controller
{
   ...
}

b) I created one method called addFlashWithParams(string $type, string $message, array $params = [])

    /**
     * Add flash session messages using parameters.
     *
     * @param string $type
     * @param string $message
     * @param array  $params
     */
    protected function addFlashWithParams(string $type, string $message,    array $params = [])
    {
        if (!$this->container->has('session')) {
            throw new \LogicException('You can not use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".');
        }

        $this->container->get('session')->getFlashBag()->add($type, ['message' => $message, 'params' => $params]);
    }

c) Created my own template which is capable to show simple flash messages (those without any parameter) and my custom flash messages.

{% for label, type in app.flashes(['info', 'warning', 'success', 'danger']) %}
    {% for index, row in type %}
        {% set message = row is iterable ?  row['message'] : row %}
        {{ label }} {{  message|trans|replace(row['params'])  }}
    {% endfor %}
{% endfor %} 

I don’t know if there’s a faster way to solve this, but this solution solved my problem! 😀

Adding flash messages with parameters is a common problem among Symfony developers and I hit the wall myself when I was working on another project which is unannounced.

I hope this post will make your life easier and hopefully, Symfony community will propose this feature in next updates.

EVOScripts
<p>Born to code.</p>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back To Top