I'm using the mailing library from zend framework 2, and also I'm using the translator functionality. But the translations only work inside the template .phtml, and not work in the service function for send the email, for example in translating the subject of the email. This is my code inside my service function to send an email:
$mailFactory = $this->getDependency('mail');
$viewModel = new ViewModel(array(
'variable' => $x
));
$viewModel->setTemplate('template.phtml');
$message = $mailFactory->prepareMessage($viewModel);
$message->getHeaders()
->addHeaderLine('MIME-Version', '1.0')
->addHeaderLine('Content-type', 'text/html; charset=UTF-8');
$message->setSubject($this->translate('Recover your password'));
$message->setEncoding("UTF-8");
$message->addTo($email, $fullname);
$transport = $mailFactory->getTransport();
return $transport->send($message);
The function $this->translate('...') calls to a class that call this code: return $this->translator->translate($text), this works well in all my application, but only works wrong when I send any email (with an exception of the template.phtml, inside this file the translator works well). All my mails received, have the subject in english (not translated) and the content in spanish (translated)
You have to pass the translator to the service to use it.
So in your module.config.php under the
service_managerkey you can do it with a factory or an initializer.Factory:
You need the method
setTranslatorin your service class!Inititalizer:
With an initializer you need the interface
TranslatorAwareInterface:And your service need to implement that interface:
In both cases you can use the translator like: