您可以创建自己的装饰器来做到这一点,像这样简单::
class My_Decorator_ElementWrapper extends Zend_Form_Decorator_Abstract
{
public function render($content)
{
$class = 'form-element';
$errors = $this->getElement()->getMessages();
if (!empty($errors))
$errors .= ' has-errors';
return '<div class="'.$class.'">' . $content . '</div>';
}
}
现在你可以为元素注册这个装饰器:
$element->addPrefixPath('My_Decorator', 'My/Decorator/', 'decorator');
$element->addDecorator('ElementWrapper');
您还可以通过使用来同时为所有元素注册前缀路径$form->addElementPrefixPath()
。
如果你想为所有元素自动添加这个装饰器(和前缀路径),我建议你扩展 Zend 对应的每个元素(例如 make My_Form_Element_Text
that extends Zend_Form_Element_Text
),然后在 init 函数中添加前缀路径,并覆盖loadDefaultDecorators()
方法ElementWrapper
在装饰器链的末尾添加。例如,这是loadDefaultDecorators()
查找的方式Zend_Form_Element_Text
:
public function loadDefaultDecorators()
{
if ($this->loadDefaultDecoratorsIsDisabled()) {
return $this;
}
$decorators = $this->getDecorators();
if (empty($decorators)) {
$this->addDecorator('ViewHelper')
->addDecorator('Errors')
->addDecorator('Description', array('tag' => 'p', 'class' => 'description'))
->addDecorator('HtmlTag', array('tag' => 'dd',
'id' => $this->getName() . '-element'))
->addDecorator('Label', array('tag' => 'dt'));
}
return $this;
}
您只需->addDecorator('ElementWrapper')
在链的末尾添加一个。所以要展示一个具体的例子My_Form_Element_Text
:
class My_Form_Element_Text extends Zend_Form_Element_Text
{
public function init()
{
$this->addPrefixPath('My_Decorator', 'My/Decorator/', 'decorator');
}
public function loadDefaultDecorators()
{
if ($this->loadDefaultDecoratorsIsDisabled()) {
return $this;
}
$decorators = $this->getDecorators();
if (empty($decorators)) {
$this->addDecorator('ViewHelper')
->addDecorator('Errors')
->addDecorator('Description', array('tag' => 'p', 'class' => 'description'))
->addDecorator('HtmlTag', array('tag' => 'dd',
'id' => $this->getName() . '-element'))
->addDecorator('Label', array('tag' => 'dt'))
->addDecorator('ElementWrapper');
}
return $this;
}
}