【问题标题】:How to customize checkbox group in Zend framework-2 form? [duplicate]如何在 Zend framework-2 表单中自定义复选框组? [复制]
【发布时间】:2013-05-29 05:08:52
【问题描述】:

其实我不明白,zend framework 2 如何为表单元素生成 HTML。例如,

$others = new Element\MultiCheckbox('others');
$others->setLabel('Others')
        ->setAttribute('name', 'others');
$others->setValueOptions(array(
    '1' => 'Contacts',
    '2' => 'Who viewd my profile'
));

此代码生成 -

<label><input type="checkbox" value="1" name="others[]">Contacts</label>
<label><input type="checkbox" value="2" name="others[]">Who viewd my profile</label>

但我需要按如下方式制作 HTML -

<input type="checkbox" value="1" name="others[]"><label>Contacts</label>
<input type="checkbox" value="2" name="others[]"><label>Who viewd my profile</label>

那么如果我想更改生成的 HTML,我该怎么做呢?

【问题讨论】:

  • 我已经检查过了,但仍然没有得到复选框组的解决方案。我可以自定义一些,但不能使用复选框组。当我写 echo $this->formElement($elements['others']);它总是生成那组代码。
  • 也许这个$others-&gt;setAttribute('name', 'others') -&gt;setLabel('Others');
  • @Amir :不,不是, setlabel('Others') 将为整个复选框组设置标签,默认情况下,每个标签内生成复选框组的每个复选框。这就是问题所在。
  • 其实你提到的两种格式的结果都是一样的。对你来说有什么不同,真的吗?

标签: php html zend-framework zend-framework2 zend-form


【解决方案1】:

对于这种功能,您需要覆盖 Zend\Form\View\Helper\MultiCheckbox 或更准确地说是它的 renderOptions() 函数。

然后让ViewHelperManager 知道$this-&gt;formMultiCheckbox() 应该调用您自己的ViewHelper 以获得所需的结果。

但是我想提一下,您正在尝试做的事情是非常不鼓励的。用户绝对应该能够点击标签!如果您要更改标记,至少要这样做:

<input type="checkbox" value="1" name="others[]" id="cbOthers1"><label for="cbOthers2">Foo</label>
<input type="checkbox" value="2" name="others[]" id="cbOthers1"><label for="cbOthers2">Bar</label>

永远不要忘记您的应用程序的可用性!另一个提示:就浏览器对样式的支持而言,标签内的 CB 会自动使您拥有更广泛的受众!话又说回来,一切都取决于你。无论如何,你必须自己写ViewHelper

PS:您的ViewHelper 会很简单,您只需将those lines 覆盖为以下内容:

  switch ($labelPosition) {
     case self::LABEL_PREPEND:
        $template  = $labelOpen . '%s'. $labelClose .'%s';
        $markup    = sprintf($template, $label, $input);
     break;
     case self::LABEL_APPEND:
     default:
        $template  = '%s' . $labelOpen . '%s'. $labelClose;
        $markup    = sprintf($template, $input, $label);
      break;
 }

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    相关资源
    最近更新 更多