Handling Zend Framework Form error messages

4 Dec

It’ll be very handy if you become able to play with Zend Form error messages. By default Zend Framework render errors messages in form of list next to each element.
Zend Form with error messages look like this.

Zend Form error messages rendered

Zend Form error messages rendered

We have a very easy way to remove these errors messages and place them wherever we like. However to do so you will need to make some changes in your form.
Just try the following form.
class forms_SimpleForm extends Zend_Dojo_Form
{
public function __construct($options = null)
{
parent::__construct($options);
$this->setMethod(‘post’);

$username=new Zend_Form_Element_Text(‘username’, array(
‘required’ => true,
‘label’ => ‘Username:’,
‘filters’ => array(‘StringTrim’, ‘StringToLower’),
‘validators’ => array(
‘Alnum’,
array(‘Regex’,
false,
array(‘/^[a-z][a-z0-9]{2,}$/’))
)
));

$username->removeDecorator(‘Errors’);

$password=new Zend_Form_Element_Password(‘password’, array(
‘required’ => true,
‘label’ => ‘Password:’,
‘filters’ => array(‘StringTrim’),
‘validators’ => array(
‘NotEmpty’,
array(‘StringLength’, false, array(6))
)
));

$password->removeDecorator(‘Errors’);

$save=new Zend_Form_Element_Submit(‘save’, array(
‘label’ => ‘save’,
‘required’=> false,
‘ignore’ => true,
));
$this->addElements(array($username, $password, $save));

}
}
?>
In the above code we have created three form elements named username, password and save. We have no concern with how we have created the Zend Form elements. In this post we are discussing error messages, so I am skipping the elements creating code.
The magic line for errors handling are
$username->removeDecorator(‘Errors’);
And
$password->removeDecorator(‘Errors’);

This two lines prevent error messages from displaying. Now if you submit the form you will find nothing next to the form elements. Form, after submission will now look like

Zend form without error messages

Zend form without error messages

We have now remove the error message from the place where they render by default. However we have not done yet. We will need to show these error message now in our view template. So place the following code into your view template where your are echoing your form.

<?php
$errorsMessages =$this->form->getMessages();
if(isset($errorsMessages[‘username’][‘isEmpty’])){
echo “Username is required field.”;
}
if(isset($errorsMessages[‘password’][‘isEmpty’])){
echo “Password is required field.”;
}
if(isset($errorsMessages[‘password’][‘stringLengthTooShort’])){
echo “Password must be more then 6 chars.”;
}

echo $this->form;
?>
The code in the “div” tag is important. In the first line we get the error messages array, check different condition and display appropriate error messages.

As you can see now you can play with these error messages and place them where ever you like. I got the following form after the submission.

Zend Form with error messages at the top

Zend Form with error messages at the top

Hope it will help you.

7 Responses to “Handling Zend Framework Form error messages”

  1. Matthew Weier O'Phinney December 4, 2008 at 3:03 pm #

    You might want to look at the FormErrors decorator added in 1.7.0; it’s purpose is precisely for what you’re describing, aggregating all errors in one place.

  2. Robert Deviasse December 5, 2008 at 12:04 am #

    Thanks for the idea. Note, however there are some significant issues. In particular, things fall apart if:
    * More validation rules are added
    * The password length changes
    * The form is localized
    * More form elements are added
    Sure you can try to keep the form code and the error code consistent, but it’s error prone….especially if new messages are added in the next version of Zend.

    Something along these lines should be able to take care of these concerns:
    foreach($this->form->getMessages() as $elemName=>$messages) {
    foreach($messages as $message) {
    $label = $form->getElement($elemName)->getLabel();
    echo $this->escape($label.’: ‘.$message).”” ;
    }
    }

    It would display error messages as:
    Username: Value is empty, but a non-empty value is required
    Password: Value is empty, but a non-empty value is required
    Password: ” is less than 6 characters long

  3. Faheem Abbas December 5, 2008 at 5:52 am #

    Thanks Matthew for your suggestion. Actually I am using ZF 1.6, and have handled my error messages the way I have discussed. I have posted this to help developer facing problems in handling errors message. I will definitely look this new future in ZF 1.7;

  4. Mondy April 23, 2009 at 7:05 pm #

    Hi, is there somewhere a tutorial, how to give a field an error class, when there is an error?
    I want to show the field which has an error in another color.

    Tahnks alot.

  5. huyby April 28, 2009 at 8:39 am #

    I’m having the same problem: how to put a css class ‘error’ on the elements when the value triggers an error?

    I bumped into this post, didn’t applied it yet because it seems complicated for such a simple task: http://stackoverflow.com/questions/534870/zend-form-how-do-i-make-it-bend-to-my-will/535512#535512

  6. Archa August 15, 2010 at 3:48 pm #

    Hi,
    Nice text, thanks for these😉

    How to get messages from EmailAddress in this -> ($errorsMessages[‘username’][‘isEmpty’]) ??

    The ($errorsMessages[‘username’][‘EmailAddress’]) dosn’t work, what will be?

    Please help Me

  7. maggi November 10, 2010 at 7:38 pm #

    how can we change the label color when validation fails??????????????

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: