Moritz Traute
Moritz Traute

Reputation: 142

Translate the Flash Message

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.

Upvotes: 9

Views: 8202

Answers (3)

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'); 
}

Upvotes: 0

Francesco Borzi
Francesco Borzi

Reputation: 61994

Alternatively, in twig:

{% for flashMessage in app.session.flashbag.get('notice') %}
    <p>{{ flashMessage|trans }}</p>
{% endfor %}

Upvotes: 4

gp_sflover
gp_sflover

Reputation: 3500

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.

Upvotes: 13

Related Questions