Reputation: 341
In one of my web projects I'm building with Zend Framework, I have a form with the following structure:
<form>
<fieldset>
<h2>Header</h2>
<ul>
<li>
<label />
<div>
<input />
<small>Helptext</small>
</div>
</li>
<li class="error"> <!-- This one has errors -->
<label />
<div>
<input />
<ul class="errors">
<li>Error message</li>
</ul>
<small>Helptext</small>
</div>
</li>
</ul>
</fieldset>
</form>
I am able to build this structure using the standard decorators of Zend Framework, except for one thing. I need to be able to add the error
class on the li of elements that have validation errors and such. I use the following validators:
'tag' => 'small', 'placement' => 'append'
)'tag' => 'div'
)'tag' => 'li'
)The default validators are disabled. (I use $element->setDecorators()
in the init()
method of a custom form class that extends Zend_Form.) So my problem boils down to adding the class "error" to the last decorator when there are any validation errors on the element.
Does anybody know a handy way to do this? I guess I could override the default render method of the elements to check if there are any validation errors and then add a class option to a named decorator, but that is not really elegant. I'm wondering if there is some standardised way to do this... I am using Zend Framework 1.11, by the way.
Cheers, Eric
Tl;dr:
How to add a class option to a HtmlTag decorator on a Zend_Form_Element when there are validation errors?
Upvotes: 1
Views: 480
Reputation: 1774
When you only want the error class for a couple of elements, you could simply use a callback for the class attribute. This would look something like the following:
$form->addElement('text', 'test', array(
'decorators' => array(
'ViewHelper',
array(
'HtmlTag',
array(
'tag' => 'li',
'class' => array(
'callback' => function($decorator) {
if($decorator->getElement()->hasErrors()) {
return 'error';
}
}
)
)
)
)
));
If you use PHP5.2 or earlier, you need to replace the closure with an array based callback (e.g. array($this, 'getLiClassAttribute')
)
If you want to use the error class for all your elements, you are better off writing a custom decorator.
Upvotes: 1