使用ZF装饰器包装标签中的复选框

时间:2012-11-10 21:28:34

标签: zend-framework zend-decorators

我在Zend Decorators(ZF1)中将复选框包装到标签中遇到了一些问题。 在我的表格中,我有一些非常简单的东西:

$remember = new Zend_Form_Element_Checkbox('remember');
$remember
    ->setLabel('Remember me');

在我的装饰者课程中:

$checkboxDecorator = array(
    'ViewHelper',
    'Errors',
    'Label',
    array('HtmlTag', array('tag' => 'div', 'class' => 'controls')),
    array('decorator' => array('Holder' => 'HtmlTag'), 'options' => array('tag' => 'div', 'class' => 'control-group')),

);

$this->setDefaultElementsDecorators($this->_checkboxElement, $checkboxDecorator);

获得的源代码如下:

<div class="control-group">
    <div class="controls">
        <label for="remember" class="optional">Remember me</label>
        <input type="hidden" name="remember" value="0">
        <input type="checkbox" name="remember" id="remember" value="1">
    </div>
</div>

我想要的是:

<div class="control-group">
    <div class="controls">
    <label for="remember" class="optional">
        <input type="hidden" name="remember" value="0">
        <input type="checkbox" name="remember" id="remember" value="1">
        Remember me
        </label>
    </div>
</div>

我测试的所有变通办法都失败了,请帮助我:P

1 个答案:

答案 0 :(得分:0)

最简单的选择是创建一个新的自定义装饰器......

class App_Form_Decorator_MyLabel
    extends Zend_Form_Decorator_Abstract
{
    public function render($content)
    {
        $el    = $this->getElement();
        $id    = htmlentities($el->getId());
        $label = htmlentities($el->getLabel());

        return '<label for="' . $id . '">' . $content . ' ' . $label . '</label>';
    }
}

然后您的$checkboxDecorator变为:

$checkboxDecorator = array(
    'ViewHelper',
    'MyLabel', // Your new class
    'Errors',
    array('HtmlTag', array('tag' => 'div', 'class' => 'controls')),
    array(
        'decorator' => array('Holder' => 'HtmlTag'),
        'options'   => array(
            'tag'   => 'div',
            'class' => 'control-group'
        )
    )
);