9

I'm trying to translate the flash message I sent, if a form is succesful. The normal request looks like this:

$request->getSession()->getFlashBag()->add(
            'notice',
            'Your E-Mail has been sent.'
        );

So I tried to translate the message with the following variable:

$request->getSession()->getFlashBag()->add(
            'notice',
            'contact.message.email_has_been_sent'
        );

After sending the form the message shows "contact.message.email_has_been_sent". So it didn't found the translation, but the variable is right. I tested it inside a template file. Has anyone an idea, how I could fix this? I didn't found anything useful yet.

Veve
  • 6,643
  • 5
  • 39
  • 58
Moritz Traute
  • 142
  • 1
  • 8

3 Answers3

13

Presuming you are in a Controller:

$request->getSession()->getFlashBag()->add(
    'notice',
    $this->get('translator')->trans('contact.message.email_has_been_sent'));

Read how to handle Translations.

gp_sflover
  • 3,460
  • 5
  • 38
  • 48
  • Since SF 2.8, you can simply do $this->addFlash(). – vctls Sep 06 '17 at 14:22
  • @VictorToulouse this is not the point of the question, but what if you don't extend the base controller of the FrameworkExtraBundle? Anyway I agree that I should expand my very "old" answer to cover all the way offered by the framework :-) – gp_sflover Sep 06 '17 at 21:03
4

Alternatively, in twig:

{% for flashMessage in app.session.flashbag.get('notice') %}
    <p>{{ flashMessage|trans }}</p>
{% endfor %}
Francesco Borzi
  • 56,083
  • 47
  • 179
  • 252
  • 1
    I would tend to prefer this method as it makes calling the translator from the controller unnecessary, but it gets complicated when you need to translate messages with placeholders. – vctls Sep 06 '17 at 14:26
  • See possible problems with this approach here: https://coderwall.com/p/ybup5a/symfony2-translating-flash-messages – Haralan Dobrev Apr 26 '18 at 11:41
0

In Symfony 5, you should inject TranslatorInterface and call trans() method passing the message id, for example:

public function method(TranslatorInterface $translator)
{
    $translator->trans('Message Id'); 
}