Get your Form validation and error messages translated in ZF2.2

Hi

I've lost quite some time with setting up i18n on my zf2.2 project, especially for form validation and error messages. So I thought: Lets make a blog post about it so you don't have to experience the same..

Let's get started

1. Configure your module's translator:

//Application/config/module.config.php
'translator' => array(
    'locale' => 'nl_BE',
    'translation_file_patterns' => array(
        array(
            'type' => 'gettext',
            'base_dir' => __DIR__ . '/../language',
            'pattern' => '%s.mo'
        ),
    ),
),

If you want to set your locale for your whole application

//config/autoload/global.php
'translator' => array(
    'locale' => 'nl_BE'
),

2. Add an alias to MvcTranslator under service_manager

//Application/config/module.config.php
'service_manager' => array(
    'aliases' => array(
        'translator' => 'MvcTranslator',
    ),
),

3. Create a .po file

//Application/language/nl_BE.po
msgid "login"
msgstr "Inloggen"

msgid "logout"
msgstr "Uitloggen"


4. And generate the mo file:

msgfmt nl_BE.po -o nl_BE.mo

Done, I thought. Translation worked for general translations and form labels. But unfortunately not for form validation messages

To get form validation messages translated, you'll need to add this to your module class

//Application\Module.php
public function onBootstrap(MvcEvent $e)
{
    $translator = $e->getApplication()->getServiceManager()->get('translator');
    AbstractValidator::setDefaultTranslator($translator);
}

Yes, that's it Happy ZF2 coding

King Foo is a SensioLabs partner