ZF2.3 translate validation message

php, zend-framework2

Solution

The solution is stated in http://framework.zend.com/manual/2.2/en/modules/zend.validator.html#translating-messages where they say: A new service has also been registered with the MVC, MvcTranslator

So you can initialize the $translator variable with

$translator = $serviceLocator->get('MvcTranslator');

You have to ensure to have access to the serviceLocator.

Problem

I am trying to translate the validation messages to another language. I am using ZF 2.3 and the skeleton application. I've configured the translator: ``` 'translator' => array( 'locale' => 'nl_NL', 'translation_file_patterns' => array( array( 'type' => 'gettext', 'base_dir' => __DIR__ . '/../language', 'pattern' => '%s.mo', ), array( 'type' => 'phpArray', 'base_dir' => __DIR__ . '/../data/language', 'pattern' => '%s.php', ), ), ), ``` But the following string is not translated in my view file (and im sure this string is included in my language file): ``` echo $this->translate('Invalid type given. String, integer or float expected'); ``` And also the messages from the validators are still default / not translated. Ive searched for solutions everywhere, but it seems like translations have been refactored in ZF 2.3, and all solutions I can find are for older versions. The following documentation page should offer a solution: http://framework.zend.com/manual/2.3/en/modules/zend.validator.messages.html But the code under 'Using pre-translated validation messages' is not working: ``` $translator = new Zend\Mvc\I18n\Translator(); $translator->addTranslationFile( 'phpArray', 'resources/languages/en.php', 'default', 'en_US' ); Zend\Validator\AbstractValidator::setDefaultTranslator($translator); ``` This will result in a fatal error: ``` Catchable fatal error: Argument 1 passed to Zend\Mvc\I18n\Translator::__construct() must implement interface Zend\I18n\Translator\TranslatorInterface, none given ``` Is there a known solution for ZF 2.3 ? Solution: In config: ``` 'service_manager' => array( 'factories' => array ( 'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory', ), ), ``` In Module bootstrap event: ``` $translator = $e->getApplication()->getServiceManager()->get('translator'); $translator->addTranslationFile('phpArray', __DIR__ . '/language_php/Zend_Validate.php', 'default', 'nl_NL'); \Zend\Validator\AbstractValidator::setDefaultTranslator(new \Zend\Mvc\I18n\Translator($translator)); ```

Original source