user827080
user827080

Reputation:

Zend_Form_Element: add class if it contains errors

In my current application, I would like to color the select options red when they contain faulty information (aka not validated). When a form element contains one or more errors, it should have an error class (so I can style accordingly). I tried looping through the elements, and seeing if they validated, but this gets very ugly very quickly.

How would I get this done in a better way?

Thanks

Edit: This is my current workaround (and gets the job done, but dirtily)

$post = $request->getPost();
foreach ($contactForm->getElements() as $element) {
    if (!$element->isValid($post[$element->getName()])) {
        $element->setAttrib('class', 'error');
    }
}

Upvotes: 5

Views: 2596

Answers (1)

drew010
drew010

Reputation: 69937

Here are a couple of thoughts...

  1. Instead of calling isValid on every form element, you can validate your whole form with isValid, and then loop over your elements as you are in your question, but instead use if ($element->hasErrors()) to determine if you need to add the error class to the element.

  2. You may want to extend from Zend_Form and add a helper method to your new Form class that does this for you. For example, add a method called highlightErrorElements() or something like that and if you have an unsuccessful call to $form->isValid(), you can then simply call $form->highlightErrorElements() which will loop over each form element and see if it has errors and apply the style if necessary.

Example:

<?php

class Application_Form_Base extends Zend_Form
{
    public function __construct()
    {
        // this is where i normally set up my decorators for the form and elements
        // additionally you can register prefix paths for custom validators, decorators, and elements

        parent::__construct();
        // parent::__construct must be called last because it calls $form->init()
        // and anything after it is not executed
    }

    public function highlightErrorElements()
    {
        foreach($this->getElements() as $element) {
            if($element->hasErrors()) {
                $element->setAttrib('class', 'error');
            }
        }
    }
}

Somewhere, in a controller...

$form = new Application_Form_Register(); // this extends Application_Form_Base
if ($form->isValid($this->getRequest()->getPost())) {
    // add user etc
} else {
    $form->highlightErrorElements();
    // other error logic
}

$this->view->form = $form;

Upvotes: 5

Related Questions