How to have a decorator applied as a default for a

2019-04-15 03:54发布

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条回答
劫难
2楼-- · 2019-04-15 04:45

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.

查看更多
登录 后发表回答