2

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.
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

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

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.

  • 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 '17 at 13:06
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, privacy policy and cookie policy

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