我将这样的设置添加到我的所有 Zend 表单中而不必为每个表单重复代码的方法是创建一个扩展 Zend_Form 的基本表单类,而我的所有其他表单都扩展了它。
在基本表单的构造函数中,我为各种类型的元素设置不同的装饰器或为我的应用程序自定义装饰器,为帮助器和验证器指定前缀路径等。
关于此方法需要注意的重要一点是,如果您的基本形式 __construct 方法,您必须在最后一行调用 parent::__construct()。原因是Zend_Form::init() 方法被Zend_Form::__construct() 调用,之后构造函数中没有其他内容运行。
这是一个例子:
<?php
class Application_Form_Base extends Zend_Form
{
// decorator spec for form elements like text, select etc.
public $elementDecorators = array(
'ViewHelper',
'Errors',
array('Description', array('tag' => 'p', 'class' => 'description', 'escape' => false)),
array('HtmlTag', array('class' => 'form-div')),
array('Label', array('class' => 'form-label', 'requiredSuffix' => '*'))
);
// decorator spec for checkboxes
public $checkboxDecorators = array(
'ViewHelper',
'Errors',
array('Label', array('class' => 'form-label', 'style' => 'display: inline', 'requiredSuffix' => '*', 'placement' => 'APPEND')),
array('HtmlTag', array('class' => 'form-div')),
array('Description', array('tag' => 'p', 'class' => 'description', 'escape' => false, 'placement' => 'APPEND')),
);
// decorator spec for submits and buttons
public $buttonDecorators = array(
'ViewHelper',
array('HtmlTag', array('tag' => 'div', 'class' => 'form-button'))
);
public function __construct()
{
// set the <form> decorators
$this->setDecorators(array(
'FormElements',
array('HtmlTag', array('tag' => 'div', 'class' => 'form')),
'Form'));
// set this as the default decorator for all elements added to the form
$this->setElementDecorators($this->elementDecorators, array('submit', 'button'), true);
// add prefix paths for decorators and validators
$this->addElementPrefixPath('My_Decorator', 'My/Decorator', 'decorator');
$this->addElementPrefixPath('My_Validator', 'My/Validator', 'validate');
parent::__construct();
// parent::__construct must be called last because it calls $form->init()
// and anything after it is not executed
}
}