【问题标题】:How to have a decorator applied as a default for all forms in Zend_Form?如何为 Zend_Form 中的所有表单默认应用装饰器?
【发布时间】:2012-01-18 10:29:09
【问题描述】:

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

$form->addError($message);

为此,我需要将相关的装饰器添加到我的表单中:

$form->addDecorator('Errors');

相当容易。问题是应用新装饰器会导致所有默认装饰器被删除,从而迫使我重新应用所有装饰器:

$form->addDecorator('Errors')
     ->addDecorator('FormElements')
     ->addDecorator('HtmlTag', array('tag' => 'dl', 'class' => 'zend_form'))
     ->addDecorator('Form');

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

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

【问题讨论】:

  • 添加装饰器不应该重置它们,setDecorators 会重置它们。我认为优雅的简单解决方案是从扩展 zend 表单本身的基类扩展所有表单。这就是我所做的,我用它来设置表单装饰器和默认元素装饰器等等。
  • 不幸的是:loadDefaultDecorators()(称为 after init())仅添加默认装饰器 if (empty($decorators))。我可能会继续使用基类解决方案。
  • 但是有一个问题:你把这些装饰器放在基类的什么地方?在init() 方法中?然后在所有子类中调用parent::init()
  • 查看我的答案here(向下滚动到“这是基类”代码块)。下一个代码块展示了如何扩展它。您不必在子类中调用 parent::init(),只需使用普通的 init 方法即可。

标签: zend-framework zend-form


【解决方案1】:

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

/**
* 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 重构。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 2011-06-28
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多