Is there any simple way to add an error class to form fields with Zend framework if validation has failed?
So far I've just fou开发者_Python百科nd out that I could write an own view helper but as I'm new to the framework I don't know how to do that. I hope there's a simpler way!?
I was just about to ask this question myself with my own solution, to provide for the community, so to speak, when I saw you question pop up in the suggestions.
My simple and pretty elegant solution, if I say so myself, uses a simple custom decorator. It does nothing to the content it receives, but it alters the element.
class App_Form_Decorator_ErrorClass
extends Zend_Form_Decorator_Abstract
{
protected $_placement = null;
protected $_options = array(
'class' => 'error'
);
public function render( $content )
{
$element = $this->getElement();
if( $element->hasErrors() )
{
$errorClass = $this->getOption( 'class' );
$currentClass = $element->getAttrib( 'class' );
$element->setAttrib( 'class', ( !empty( $currentClass ) ? $currentClass . ' ' . $errorClass : $errorClass ) );
}
return $content;
}
}
Usage:
All you need to do is add the decorator before the ViewHelper decorator, and your set.
public function init()
{
$elementDecorators = array(
'ErrorClass',
'ViewHelper',
// etc..
);
// or:
$elementDecorators = array(
array(
'ErrorClass',
array( 'class' => 'custom-class' ) // defaults to 'error'
),
'ViewHelper',
// etc..
);
// then just add the decorators to an element the way you usually do, for instance like so:
$someElement = new Zend_Form_Element_Text( 'someElement' );
$someElement->setDecorators( $elementDecorators );
// etc...
O, PS.: Be sure to add the correct prefix path in your form:
$this->addPrefixPath( 'App_Form', 'App/Form' ); // or your own namespace
Yes use Dojo javascript library (although setting it up can be a little hard) Try this to get you started http://techchorus.net/add-cool-zend-dojo-date-picker-form-element-without-writing-single-line-javascript
This is how it looks :
The simplest way i found to do this was extending the isValid() method of the corresponding Form Class in use, preferrably set into a My_Standard_Form Class in your library.
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;
}
Credits for the solution go to the Website Factors Blog (http://www.websitefactors.co.uk/zend-framework/2011/06/error-class-on-form-field-errors-using-zend-form/).
精彩评论