phpzend-framework2zend-form2

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


I have a form with Radio-button:

$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'
]);

In the view I make the output like this:

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

and get the output (formatted for readability):

<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>

But I need, that label text ist wrapped by a <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>

What is the best way to achieve it?


Solution

  • I see three possible solutions for your problem.

    1) Extend the Zend\Form\View\Helper\FormRadio class, overriding the renderOptions method, replicating almost entirely the one that you can find in Zend\Form\View\Helper\FormMultiCheckbox but maybe adding an option to pass optional attributes to the span element

    2) Very subtle, but could save you writing some code: using the translator. Since the radio value options are translated, you could keep your values defined in the configuration but adding the span element in the transation

    3) Do not use $this->formElement to display the element, but actually write all the html