King Foo

King Foo

You are in:

King Foo > Blog > PHP > Zend Framework > Get your Form validation and error messages translated in ZF2.2


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

Posted by


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:

'translator' => array(
    'locale' => 'nl_BE',
    'translation_file_patterns' => array(
            'type' => 'gettext',
            'base_dir' => __DIR__ . '/../language',
            'pattern' => ''

If you want to set your locale for your whole application

'translator' => array(
    'locale' => 'nl_BE'

2. Add an alias to MvcTranslator under service_manager

'service_manager' => array(
    'aliases' => array(
        'translator' => 'MvcTranslator',

3. Create a .po file

msgid "login"
msgstr "Inloggen"

msgid "logout"
msgstr "Uitloggen"

4. And generate the mo file:

msgfmt nl_BE.po -o

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

public function onBootstrap(MvcEvent $e)
    $translator = $e->getApplication()->getServiceManager()->get('translator');

Yes, that’s it
Happy ZF2 coding

  1. 25/02/2014


    Hi, i get an error when i add an alias to MvcTranslator under service_manager:

    An alias by the name “translator” or “translator” already exists

    Don’t know what to do about it. Can you help me out?

    • 18/03/2014


      Hi ProX

      Thanks for your question!
      You’re probably already have defined another service with the name “translation” in another configuration file, which is fine.
      You can just change the name of translator here to any other name you like (ie. translatorFoo)
      but make sure that you get the right service in your module

      $translator = $e->getApplication()->getServiceManager()->get('translatorFoo');

      Hope this helps.


  2. 24/10/2013

    Jeroen Keppens

    How would you generate the initial PO document based on your code? I’m used to using POEdit, but I like this approach.

  3. 22/08/2013

    Cristiano Teles

    Good text, just missed the namespace of the adapter:

    Thank you
    Cristiano Teles

Leave a comment

Please wrap all source codes with [code][/code] tags.
  1. Translated in ZF2 – denismendes09-07-14