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!
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With