Lal Mohan
Lal Mohan

Reputation: 323

How to set locale in command class symfony2.1

I am using command class for sending cron mail. How can I set the locale for sending email like?

$this->getRequest()->setLocale('de'); 

In my case each user have different locale. How can I set the locale in command class?

I tried $this->getRequest()->setLocale('de'); and getting an error:

namespace IT\bBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;  
use Symfony\Component\Console\Input\InputArgument;  
use Symfony\Component\Console\Input\InputInterface;  
use Symfony\Component\Console\Input\InputOption;  
use Symfony\Component\Console\Output\OutputInterface;

class CronCommand extends ContainerAwareCommand {
    protected function configure()
    {
        $this
            ->setName('send:emails')
            ->setDescription('Envio programado de emails');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $message = \Swift_Message::newInstance()
            ->setSubject('bla bla')
            ->setFrom('[email protected]')
            ->setTo('[email protected]')
            ->setCharset('UTF-8')
            ->setContentType('text/html')       
            ->setBody($this->renderView('mainBundle:Email:default.html.twig'));

        $this->getContainer()->get('mailer')->send($message);
        $output->writeln('Enviado!');
    } }

Upvotes: 2

Views: 4021

Answers (2)

Lal Mohan
Lal Mohan

Reputation: 323

I solved the issue, I used:

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

To set locale in command class for cron mail translation.

Upvotes: 9

Michael
Michael

Reputation: 2331

When you have a ContainerAwareCommand, you can read the value from your config file and insert it into the translator manually like this: (Tested in SF 2.8)

$locale = $this->getContainer()->getParameter('locale');
$this->getContainer()->get('translator')->setLocale($locale);

Upvotes: 1

Related Questions