Error Class On Form Field Errors Using Zend Form

One of the most powerful components of Zend Framework is Zend Form. In this article, I will show you how to put an error class on your form field when using Zend Form. This enables you to create a css class to style the form field in the instance of an error.

Extend Zend Form class:

Here we create a form class that extends Zend_Form. We override the isValid() method. We loop through the form->elements and add a class of “error” if the hasErrors() method returns true. We also do a check to see if a class attribute already exists using the getAttrib() method and if so we append the “error” class using a space to separate.

class MyForm extends Zend_Form
{
    public function isValid($data)
    {
        $valid = parent::isValid($data);
 
        foreach ($this->getElements() as $element) {
            if ($element->hasErrors()) {
                $oldClass = $element->getAttrib('class');
                if (!empty($oldClass)) {
                    $element->setAttrib('class', $oldClass . ' error');
                } else {
                    $element->setAttrib('class', 'error');
                }
            }
        }
 
        return $valid;
    }
}

Now, when you call the isValid method, it will automatically add a class of error to any fields that do not pass validation.

Here’s an example of a form field with the error class after a validation attempt:

Error Form Field Example

Error Form Field Example

Permalink: http://www.websitefactors.co.uk/zend-framework/2011/06/error-class-on-form-field-errors-using-zend-form/

This entry was posted in Zend Framework. Bookmark the permalink.

3 Responses to Error Class On Form Field Errors Using Zend Form

  1. Paul Poulet says:

    Thank you for this tip!

  2. BehRang says:

    Hi,
    It’s works fine on forms but I can’t use this method on subforms any idea?

    • Henry Hayes says:

      Yeah – this will work on any Zend_Form type class. My example above only shows you how to implement it on the main form, but there’s no reason why you can’t implement this into a subform.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Notify me of followup comments via e-mail. You can also subscribe without commenting.