Reputation: 957
I have a custom markup for my zend_form and i try to set a css class (class="hasErrors") to my input field. My rendered form elements look like this:
<div id="teamname-element" class="formRow">
<input type="text" name="teamname" id="teamname" value="" placeholder="Teamname">
</div>
with errors it looks like this:
<div id="teamname-element" class="formRow">
<input type="text" name="teamname" id="teamname" value="" placeholder="Teamname">
<ul class="errors">
<li>Your teamname is to short!</li>
</ul>
</div>
is it possible to set a css class to the input field without using javascript?
<input class="hasErrors" type="text" name="teamname" id="teamname" value="" placeholder="Teamname">
A form element is created like this:
$this->addElement(new Nut_Form_Element_Text('teamname', array(
'Label' => 'Teamname',
'validators' => array( array('StringLength', FALSE, array(1, 25)), $TeamRegex),
'filters' => array('StringTrim', 'StripTags'),
)));
Upvotes: 1
Views: 386
Reputation: 2370
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 . ' hasError');
} else {
$element->setAttrib('class', 'hasError');
}
}
}
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.
Upvotes: 1