ihsan
ihsan

Reputation: 2289

symfony2: how to use translator in console command

I'm trying to use translator in symfony2 (2.3.0) console command, but I can't make it work. Here is what I've done so far:

use Symfony\Component\Translation\IdentityTranslator;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class SendMessageCommand extends ContainerAwareCommand
{
    protected function configure() {
        $this->setName('mycommand:sendmessage')->setDescription('send message.');
    }

    protected function execute(InputInterface $input, OutputInterface $output) {
        $translator = $this->getContainer()->get('translator');

        echo $translator->trans('my.translation.key'); // not working
    }
}

my.translation.key is exists in messages.yml. Any idea how to make it work?

thanks!

Upvotes: 4

Views: 4451

Answers (1)

ihsan
ihsan

Reputation: 2289

I just found that in symfony2 console command, the default locale defined in config.yml is never used so the locale is NULL. So the translator will never use any translations locale available. That's why the translation key is returned intact instead of the translation.

I got this hint when I run only the console command which is trying to translate something, but the catalogue in app/cache/dev/translations folder is not generated.

So, this is how I do to make translations in console command works (in my case, I set it to id_ID):

$translator = $this->getContainer()->get('translator');
$translator->setLocale("id_ID");

echo $translator->trans('my.translation.key'); // works fine! :)

Hope that could help anyone facing the same problem. :)

Upvotes: 9

Related Questions