问题
I need to display form-level errors in my forms (errors that do not belong to one field, but to the whole form submission), with this code:
$form->addError($message);
For this to work, I need to add the relevant decorator to my form:
$form->addDecorator('Errors');
Fairly easy. The problem is that applying a new decorator causes all default decorators to be removed, thus forcing me to re-apply all of them:
$form->addDecorator('Errors')
->addDecorator('FormElements')
->addDecorator('HtmlTag', array('tag' => 'dl', 'class' => 'zend_form'))
->addDecorator('Form');
This is some redundant code I have in most of my forms. Is it possible to have the Errors
decorator part of the default decorators, by applying some setting?
I could obviously create an abstract Form
class to inherit from, but I'm wondering if I'm missing a simpler or more elegant solution.
回答1:
You can override the loadDefaultDecorators method to create a form class that support errors like:
/**
* Form with error decorator included by default
*/
class ErrorForm extends Zend_Form {
public function loadDefaultDecorators() {
$this->addDecorator('Errors');
$decoratorsWithError = $this->getDecorators();
//clearing to let the parent do default business
$this->clearDecorators();
parent::loadDefaultDecorators();
//union decorators array so error is first
$finalDecorators = $decoratorsWithError + $this->getDecorators();
//finally
$this->setDecorators($finalDecorators);
return $this;
}
}
Errors decorator should be the first one to render. I think more elegant solution would require Zend_Form refactoring.
来源:https://stackoverflow.com/questions/8908580/how-to-have-a-decorator-applied-as-a-default-for-all-forms-in-zend-form