Zend_Form_Element: add a class if it contains errors

In my current application, I would like to color the selection options in red when they contain erroneous information (it has not been verified). If a form element contains one or more errors, it must have an error class (so I can change the style accordingly). I tried to navigate through the elements and see if they were checked, but it is very ugly very quickly.

How to do it better?

thank

Edit: This is my current solution (and does the job, but is dirty)

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

Here are a couple of thoughts ...

  • isValid isValid, , , if ($element->hasErrors()), , .

  • , Zend_Form Form, . , highlightErrorElements() - , $form->isValid(), $form->highlightErrorElements(), , .

:

<?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');
            }
        }
    }
}

- ...

$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;
+5

All Articles