How to set class for the radio buttons set's container in a ZF2 Form?

479 Views Asked by At

In my form I have a radio buttons set foo defined as follows:

$this->add(
    [
        'type' => 'radio',
        'name' => 'foo',
        'options' => [
            'label' => 'foo',
            'value_options' => [
                [
                    'value' => Foo::BAR,
                    'label' => 'bar'
                ],
                [
                    'value' => Foo::BUZ,
                    'label' => 'buz'
                ]
            ],
            'label_attributes' => [
                'class' => 'col-md-12',
            ]
        ],
        'attributes' => [
            'class' => 'field-foo'
        ]
    ]);

In the view script it's called like this:

$this->formRow($myFieldset->get('foo'));

So I get this HTML:

<fieldset>
    <legend>foo</legend>
    <label class="col-md-12">
        <input type="radio" value="bar" class="field-foo" name="my_fieldset[foo]">bar
    </label>
    <label class="col-md-12">
        <input type="radio" value="buz" class="field-foo" name="my_fieldset[foo]">buz
    </label>
</fieldset>

Now I want to mark this radio buttons set as required. For input[type="text"] fields I manage that via label:

label.required:before {
    content: '* ';
    color: #ff0000;
}

In this case I need to access the legend or at least the fieldset, in order to define

fieldset > legend.required:before, /*or*/
fieldset.required > legend:before {
    content: '* ';
    color: #ff0000;
}

How to do this? How to set a class for fieldset / legend element of a radio buttons set in Zend Framework 2?

1

There are 1 best solutions below

0
leoap On

I don't think you're able to do this through options. But you can use partials to template your inputs:

$this->formRow($myFieldset->get('foo'), null, null, 'path/to/partials/some-partial-file.phtml');

In this file, you can customize the way your input will be rendered, adding what you need:

<?php
/**
 * @var \Zend\Form\Element\Radio $element
 */

$element_options = $element->getValueOptions();
$element_attributes = $element->getAttributes();
$element_value = $element->getValue();
?>
<fieldset>
    <legend><?php echo $element->getLabel(); ?> * </legend>
    <?php foreach($element_options as $key => $value) { ?>

    <label class="col-md-12">
        <input type="radio" value="<?php echo $value['value']; ?>" class="field-foo" name="<?php echo $element_attributes['name']; ?>[]"><?php echo $value['value']; ?>
    </label>
    <?php } ?>
</fieldset>

Zend passes to partials an $element variable that holds your form input element