Skip to content

howto - zend framework 2 - form multilingual error messages and labels

Since the first time working with the new zend framework 2 form elements, i like it. Everybody who had the pleasure to deal with the form class from zend framework 1 will agree on that. But after a little bit of playing around with it, i had to build a form that works with multiple languages and has a lot of mandatory fields. Since you are injecting a filterclass with validators into the form, you have to create the error message inside the filter class and like:

//part of a form filter constructor $this->add( array( 'name' => 'name', 'filters' => array( array( 'name' => 'StringTrim' ) ), 'validators' => array( array( 'name' => 'NotEmpty', 'options' => array( 'messages' => array( \Zend\Validator\NotEmpty::IS_EMPTY => 'I am the error message that should be multilingual.' ) ) ) ) ) );
So my first idea was to inject a translator. Since you are using a "MyMagicFormFactory" to create the form, you can easily inject the translator (or the servliceLocator if you want to). But after a few thoughts, i figured out that the error message itself is totally wrong on that place, for my point of view. I thing a form as well as a filter is not responsible for a human readable error message. Thats why i moved/reset the definition of the error message and handle it in the template. Of course, i am also using the translator but now only in the view layer. By the way, i will deal the same way with the labels for each form element.

So the simple question is how to deal with it? To keep it simple, i will not use the translator inside the following example. Assuming you a form with a input field for an email address. You can deal with it the following way.

<?php echo $this->form()->openTag($this->form); ?> <dl> <dt> <!-- we don't use the method ->getOption('lable') since we want to deal the multiple languages inside the template --> Your mail address </dt> <dd> <?php echo $this->formEmail($this->form->get('email)); $messages = $this->form->get('from')->getMessages(); //take a look inside the $messages since it is an array with keys like 'isEmpty' // if you want to create error messages by key, thats the way you can handle this. if (!empty($messages)) { echo '<label for="from" class="error">Please insert a valid email address.</lable>'; } ?> </dd> </dl>
Enjoy working with zend framework 2 :-).