user1077915
user1077915

Reputation: 894

Cakephp 3 - custom class for radio input label

I'm creating a multi-radio passing options as :

$this->Form->radio(
    'edu_tests_items.0.edu_sheets_items_grade_id',
     $eduSheetsGradesItems,
     ['autocomplete' => 'off']
);

The content of every $eduSheetsGradesItems is like :

(int) 0 => [
    'value' => (int) 1,
    'text' => 'Mal',
    'label' => [
        'class' => 'btn btn-danger'
    ],
    'class' => 'btn btn-danger'
],

Then I got this html for every radio button group ( here I show only the first label element )

<input name="edu_tests_items[0][edu_sheets_items_grade_id]" value="" type="hidden">
<label for="edu-tests-items-0-edu-sheets-items-grade-id-1">
    <input
        name="edu_tests_items[0][edu_sheets_items_grade_id]"
        value="1"
        class="btn btn-danger"
        id="edu-tests-items-0-edu-sheets-items-grade-id-1"
        autocomplete="off"
        type="radio">
    Mal
</label>

What I'm trying to do is to set a specific class ( different for every radio button label ) for the label element ( btn btn-danger in the example ) but I cannot figure out how.

Upvotes: 0

Views: 813

Answers (1)

ndm
ndm

Reputation: 60453

The radio widget doesn't support individual radio label configuration, it only supports configuration for all labels (current not properly documented in the Cookbook), which can be passed via the radio() methods third argument, like:

$this->Form->radio(
    'edu_tests_items.0.edu_sheets_items_grade_id',
    $eduSheetsGradesItems,
    [
        'autocomplete' => 'off',
        'label' => [
            'class' => 'btn btn-danger'
        ]
    ]
);

You could configure this via templates too, which would however only work using the FormHelper::control/input() method, but you don't really have to.

So if you want to apply the same class to all labels, then the above will do it. If you need to apply different classes do different labels, then you'll have to go with a custom widget, and for example extend the Cake\View\Widget\RadioWidget and override the RadioWidget::_renderLabel() method to support possible label keys in the $radio argument, which maps to your individual option-set.

Here's a quick & dirty example:

protected function _renderLabel($radio, $label, $input, $context, $escape)
{
    if ($label &&
        isset($radio['label'])
    ) {
        $label = is_array($label) ? $label : [];

        if (isset($label['class'])) {
            $radio['label'] = $this->_templates->addClass($radio['label'], $label['class']);
        }

        $label = $radio['label'] + $label;
    }

    return parent::_renderLabel($radio, $label, $input, $context, $escape);
}

See also

Upvotes: 2

Related Questions