I'm using Drupal 8 with the Form API and the AJAX API, now I want to add a custom CSS class to every checkbox label, because I need to use the bootstrap custom checkboxes.
PHP (slimmed):
$form['colors'] = array(
'#type' => 'checkboxes',
'#options' => array('1' => $this->t('Black'), '2' => $this->t('White')),
'#attributes' => [
'class' => ['custom-control-input'],
],
'#prefix' => '<div class="foobar">',
'#suffix' => '</div>'
);
HTML Result (please notice every label has the class "option"):
<div class="custom-control custom-checkbox">
<div class="foobar">
<div id="edit-colors" class="form-checkboxes">
<div class="js-form-item form-item js-form-type-checkbox form-item-colors-1 js-form-item-colors-1">
<input
class="custom-control-input form-checkbox"
data-drupal-selector="edit-colors-1"
data-msg-required="Black is required."
type="checkbox"
id="edit-colors-1"
name="colors[1]"
value="1"
/>
<label for="edit-colors-1" class="option">Black</label>
</div>
<div class="js-form-item form-item js-form-type-checkbox form-item-colors-2 js-form-item-colors-2">
<input
class="custom-control-input form-checkbox"
data-drupal-selector="edit-colors-2"
data-msg-required="White is required."
type="checkbox"
id="edit-colors-2"
name="colors[2]"
value="2"
/>
<label for="edit-colors-2" class="option">White</label>
</div>
</div>
</div>
</div>
My Twig Code:
<div class="custom-control custom-checkbox">
{{form.colors}}
</div>
I know about the "template_preprocess_form_element" function, but I had no luck.
Do you guys have any ideas or tipps? Is there a simple way to modify the label class, or should I try the "Form Options Attributes" Plugin?
Thanks