Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change locale multiple times in symfony command

I'm trying to send reminders to users through a symfony 2.0 command (called by a cron). The thing is that our website is multilingual (default is French).

I'm setting the locale at each step of the loop that sends the reminders. The locale is correctly set the first time. But in subsequent steps, it's as if the latest locale change did not reflect in the template, and the template is translated to the locale of the first step.

I'm wondering how I could fix it so that the locale change is reflected.

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('[email protected]' => '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
?>

Thanks for your help!

like image 655
ChMat Avatar asked Nov 14 '12 15:11

ChMat


1 Answers

Try to add

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

Because locale saved at translator only at its initialization, but not when trans() is called

like image 85
Ziumin Avatar answered Sep 28 '22 06:09

Ziumin