我在Zend_Config_Ini中有以下默认装饰器来设置我的表单:
elementDecorators.viewHelper.decorator = "ViewHelper"
elementDecorators.label.decorator = "Label"
elementDecorators.errors.decorator = "Errors"
elementDecorators.htmlTag.decorator = "HtmlTag"
elementDecorators.htmlTag.options.tag = "li"
Zend_Config_Ini中也有以下元素定义:
elements.username.type = "text"
elements.username.options.label = "Username:"
elements.username.options.required = true
并产生以下输出:
<li>
<label for="username" class="required">Username:</label>
<input type="text" name="username" id="username" value="" />
</li>
现在我需要知道的是,我如何(最好通过ini配置文件)设置LI标记的id或类?我想要以下输出:
<li id="form-username-element"> ... </li>
或
<li class="form-2col"> ... </li>
更新:我能够通过重写元素配置中的所有装饰器来获得它,如下所示:
elements.username.options.decorators.viewHelper.decorator = "ViewHelper"
elements.username.options.decorators.label.decorator = "Label"
elements.username.options.decorators.errors.decorator = "Errors"
elements.username.options.decorators.htmlTag.decorator = "HtmlTag"
elements.username.options.decorators.htmlTag.options.tag = "li"
elements.username.options.decorators.htmlTag.options.class = "username-row-element"
因此,这将起作用,但会产生大量重复,因为这将必须应用到每个元素上(最后一行的单个更改将是类设置本身)。因此,我现在想知道的是,从ini文件中,是否有一种方法可以使用默认的装饰器来覆盖类名(而不必为每个元素复制所有的装饰器)?
最简单的事情就是创建自己的装饰器。例如,我创建了一个ElementWrap装饰器,它用div包装每个元素,并添加必要的类和id
class Form_Decorator_ElementWrap extends Zend_Form_Decorator_Abstract
{
public function render($content)
{
$element = $this->getElement();
if($this->getOption('openOnly')) {
return '<div class="'.$this->getClass().'" id="'.$this->getId().'">' . $content;
} else if($this->getOption('closeOnly')) {
return $content . PHP_EOL . '</div>' . PHP_EOL;
} else {
return '<div class="'.$this->getClass().'" id="'.$this->getId().'">' . $content . '</div>';
}
}
public function getClass()
{
$element = $this->getElement();
$classes = array(
'field_wrap',
'field_' . strtolower(substr(strrchr($element->getType(), '_'), 1)),
$this->getOption('class'),
);
if($element->hasErrors()) {
$classes[] = 'field_error';
}
if($elementClass = $element->getAttrib('class')) {
$classes[] = $elementClass;
}
return implode(' ', array_filter($classes));
}
public function getId()
{
return 'fieldwrap-' . $element->getId();
}
}