本文介绍了如何将装饰器应用为 Zend_Form 中所有表单的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的表单中显示表单级别的错误(错误不属于一个字段,而是属于整个表单提交),代码如下:

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');

这是我的大多数表单中的一些冗余代码.通过应用一些设置,是否可以将 Errors 装饰器作为默认装饰器的一部分?

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?

我显然可以创建一个抽象的 Form 类来继承,但我想知道我是否缺少一个更简单或更优雅的解决方案.

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.

推荐答案

您可以重写 loadDefaultDecorators 方法来创建支持以下错误的表单类:

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;
    }

}

错误装饰器应该是第一个渲染的.我认为更优雅的解决方案需要 Zend_Form 重构.

Errors decorator should be the first one to render. I think more elegant solution would require Zend_Form refactoring.

这篇关于如何将装饰器应用为 Zend_Form 中所有表单的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 06:47