3

I'm developing a command line module in magento 2 and I cannot find a way to set locale programmatically.

The module takes care of creating a pdf invoice from an order and sends it via email to customer. All is going fine but the mail and the pdf invoice are in english.

Also if I try to print something like echo __('my phrase'), and I have the corresponding translation in /i18n/it_IT.csv file, it doesn't print the translated sentence.

I'm stuck there since 8h or so, trying a bunch of ways to do that.

If I instantiate a local resolver instance (Magento\Framework\Locale\ResolverInterface) via objectManager or injecting it in the constructor and then try $this->_localResolver->getLocale(), it prints it_IT, but nothing happens.

Here is a piece of my code:

$locale = $objectManager->create('Magento\Framework\Locale\ResolverInterface');
echo $locale->getLocale();  //it prints 'it_IT'
$locale->setLocale('it_IT');
$locale->setDefaultLocale('it_IT');

echo __('Price including VAT') . "\n\r"; //It prints 'Price including VAT' and not the translated sentence.

3 Answers 3

2

Ok following Raphael suggestions I found how to set locale and enable traslations in a command CLI module:

    /** @var Magento\Framework\TranslateInterface */
    $localeInterface = $this->_objectManager->get('Magento\Framework\TranslateInterface');
    $localeInterface->loadData();
    // Inizializing \Magento\Framework\Phrase 
    \Magento\Framework\Phrase::setRenderer($this->_objectManager->get('Magento\Framework\Phrase\RendererInterface'));

Hope this could be usefull to someone else.

1
  • i try this solution but its not working on my end could you pls describe me in detail i need to set locale programmatically.
    – Pratik
    May 15, 2017 at 13:06
1

I'm pretty sure setting the locale of Magento\Framework\Locale\ResolverInterface is not enough as this is only for the locale resolver.

I reckon you also need to to set the locale interface locale by calling:

$localeInterface = $objectManager->create('Magento\Framework\TranslateInterface');
$localeInterface->setLocale('it_IT');

NB: do not use the object manager directly, the code above is just an example on how to do it.

If this still does not work I suggest you check this thread in details to start debugging your problem: https://magento.stackexchange.com/a/106294/2380

2
  • Hi Raphael, it doesn't work :(
    – floyd
    Oct 25, 2016 at 13:13
  • @floyd see my updated answer to help you debug your issue Oct 25, 2016 at 13:16
0

I build a Translation Helper as Example for Magento2.

You can find here:

https://gist.github.com/larsroettig/45af9c1746bbb61c273067136c06700d

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.