How to create custom Radio-Button shortcuts 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 conclude as follows:

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

and get the result (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 the label text to be wrapped <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?

+4
source share
2 answers

I see three possible solutions to the problem.

1) Extend the class Zend\Form\View\Helper\FormRadioby overriding the method renderOptions, completely copying the one you can find in Zend\Form\View\Helper\FormMultiCheckbox, but possibly adding an option to pass optional attributes to the elementspan

2) , , : . , , , span

3) $this->formElement , html

0

, 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]);
0

Source: https://habr.com/ru/post/1620565/


All Articles