如何在 ZF2 表单中制作自定义单选按钮标签?

How to make custom Radio-Button labels in ZF2 forms?

我有一个带有单选按钮的表单:

$this->add([
    'name' => 'time',
    'options' => [
        'value_options' => [
            '0' => '9:00 - 12:00',
            '1' => '12:00 - 16:00',
            '2' => '16:00 - 19:00',
        ],
        'label_attributes' => [
            'class' => 'WW_OBJ_fm-label',
        ]
    ],
    'type' => 'Radio'
]);

在视图中我的输出是这样的:

<div> 
<?php echo $this->formElement($form->get('time')); ?>
</div>

并获得输出(为了便于阅读而格式化):

<div>
    <label class="WW_OBJ_fm-label">
        <input type="radio" name="time" value="0"/>
        9:00 - 12:00
    </label>
    <label class="WW_OBJ_fm-label">
        <input type="radio" name="time" value="1"/>
        12:00 - 16:00
    </label>
    <label class="WW_OBJ_fm-label">
        <input type="radio" name="time" value="2"/>
        16:00 - 19:00
    </label>
</div>

但我需要,标签文本由 <span>:

包裹
<div>
    <label class="WW_OBJ_fm-label">
        <input type="radio" name="time" value="0"/>
        <span class="WW_label-text">9:00 - 12:00</span>
    </label>
    <label class="WW_OBJ_fm-label">
        <input type="radio" name="time" value="1"/>
        <span class="WW_label-text">12:00 - 16:00</span>
    </label>
    <label class="WW_OBJ_fm-label">
        <input type="radio" name="time" value="2"/>
        <span class="WW_label-text">16:00 - 19:00</span>
    </label>
</div>

实现它的最佳方法是什么?

一个解决方案是使用 labelOption 'disable_html_escape' :

$this->add([
        'name' => 'time',
        'options' => [
            'value_options' => [
                '0' => '<span class="WW_label-text">9:00 - 12:00</span>',
                '1' => '<span class="WW_label-text">12:00 - 16:00</span>',
                '2' => '<span class="WW_label-text">16:00 - 19:00</span>',
            ],
            'label_attributes' => [
                'class' => 'WW_OBJ_fm-label',
            ]
        ],
        'type' => 'Radio'
    ]);
$element = $this->get('time');
$element->setLabelOptions(['disable_html_escape' => true]);

我看到三种可能的解决方案。

1) 扩展 Zend\Form\View\Helper\FormRadio class,覆盖 renderOptions 方法,几乎​​完全复制您可以在 Zend\Form\View\Helper\FormMultiCheckbox 中找到的方法,但可能会添加一个选项将可选属性传递给 span 元素

2) 非常微妙,但可以节省您编写一些代码:使用翻译器。由于单选值选项已翻译,您可以保留配置中定义的值,但在 transation

中添加 span 元素

3) 不要用$this->formElement显示元素,而是把html

全部写出来