【问题标题】:Zend form checkbox label before input输入前 Zend 表单复选框标签
【发布时间】:2013-09-16 12:44:08
【问题描述】:

花了几个小时在谷歌上爬行,我需要在复选框列表上实现 jQuery 按钮,我遇到的问题是当我输出表单元素时,代码将 INPUT 插入其中,而我需要它在标签之外。这是它的输出方式:

<label for="checkbox-1"><input type="checkbox" name="checkbox[]" id="checkbox-1" value="1" checked="checked">3DCrafter</label>

这是我的带有装饰器的表单元素:

$checkbox->addMultiOption($prev,$p);
        $checkbox->setAttrib('id', 'checkbox');
        $checkbox->setSeparator('  ');
        $checkbox->setDecorators(array(
           array('ViewHelper'),
           array('Errors', array('tag' => 'div', 'class' => 'error')),
           array('Label', array('tag' => 'span')),
           array('HtmlTag', array('tag' => 'div', 'class' => 'label')),
        ));

这是我输出表单元素的方式:

<?php echo $this->formSoftware->checkbox;?>

有人知道如何做到这一点吗?还是在 Zend 中的复选框上使用 jQuery 按钮?

【问题讨论】:

  • 能否请您添加您想要的预期 html 输出?

标签: jquery zend-framework zend-form


【解决方案1】:

一个(不是很令人满意的)解决方案是使用 jQuery 按预期设置 DOM:

//HTML
//the checkboxes are children of their associated label
<div id="container">
    <label for="cb1"><input type="checkbox" id="cb1" name="cb1" />Checkbox 1</label>
    <label for="cb2"><input type="checkbox" id="cb2" name="cb2" checked="checked" />Checkbox 2</label>
    <label for="cb3"><input type="checkbox" id="cb3" name="cb3" />Checkbox 3</label>
</div>

//javascript
//for each label : find its target input among its descendants,
//and place it before the label
$('#container').find('label').each(function () {
    var id = $(this).attr('for');
    $(this).find('#' + id).insertBefore(this);
});

$('#container').buttonset();

fiddle

【讨论】:

    【解决方案2】:

    如果您使用的是 ZF1,我建议您创建一个自定义装饰器类 extends Zend_Form_Decorator_Abstract,并通过在表单中​​添加 addElementPrefixPath 来注册自定义装饰器的路径。

    您的自定义装饰器将需要一个 render() 方法来输出您想要的标记。

    不确定它在 ZF2 上是如何工作的。

    【讨论】:

      【解决方案3】:

      默认情况下,标签装饰器会添加到提供的内容之前;这可以通过指定以下“放置”选项之一来控制:

      PREPEND:在内容之前渲染标签。

      APPEND:在内容之后渲染标签。

      IMPLICIT_PREPEND:在标签标签内渲染元素,将标签文本放在内容之前。

      IMPLICIT_APPEND:渲染标签标签内的元素,将标签文本放在内容之后。

      所以在你的情况下,我认为你想要 PREPEND:

      $checkbox->addMultiOption($prev,$p);
              $checkbox->setAttrib('id', 'checkbox');
              $checkbox->setSeparator('  ');
              $checkbox->setDecorators(array(
                 array('ViewHelper'),
                 array('Errors', array('tag' => 'div', 'class' => 'error')),
                 array('Label', array('tag' => 'span', 'placement' => 'PREPEND')),
                 array('HtmlTag', array('tag' => 'div', 'class' => 'label')),
              ));
      

      【讨论】:

      • 感谢您的建议,我添加了代码,但它仍然遗憾地将输入放在标签之间。
      【解决方案4】:

      这里的getLabel()方法会帮你打印Label。

      <?php echo $this->formSoftware->checkbox->getLabel();?>
      <?php echo $this->formSoftware->checkbox;?>
      

      【讨论】: