Changing the locale several times in the symfony command

I am trying to send reminders to users through a symfony 2.0 command (called cron). The fact is that our site is multilingual (French by default).

I set the locale at each step of the loop that sends reminders. The language is installed correctly for the first time. But in the next steps, it is as if the last locale change was not reflected in the template, and the template is transferred to the locale of the first step.

I am wondering how I can fix this to reflect a change in locale.

Here is some code (simplified) for reference:

<?php // This loop is inside the execute() function of a symfony service (implements ContainerAwareCommand) // โ€ฆ // Sending reminders one at a time foreach ($reminders as $reminder) { $message = \Swift_Message::newInstance(); $message->setFrom(array(' noreply@domain.com ' => 'YourBot')); // Change locale to that of the user $this->getContainer()->get('session')->setLocale($reminder->getLocale()); $templating = $this->getContainer()->get('templating'); // Reminder text $email_message = $templating->render('MyBundle:Reminder:reminder.html.twig'); $message->setSubject('Reminder') ->setTo($reminder->getEmail()) ->setBody($email_message, 'text/html'); $this->getContainer()->get('mailer')->send($message); // Update reminder status $reminder->setEmailSent(true); $emSymfony->persist($reminder); } // โ€ฆ subsequent code ?> 

Thank you for your help!

+4
source share
1 answer

Try to add

 $this->getContainer()->get('translator')->setLocale($reminder->getLocale()); 

Since the language standard is saved on the translator only when it is initialized, but not when trans () is called

+5
source

Source: https://habr.com/ru/post/1446030/


All Articles