I am displaying checkboxes using form API in Drupal 8. For functional and theming purpose I need to add unique custom class to each checkbox element. Is there any way to add classes to each checkbox elements on wrapper/label/input level?
Here is my form API for checkbox element.
public function buildForm(array $form, FormStateInterface $form_state,
$items = array()) {
$tids = [5,8,7,9,3,1,45];
$terms = Term::loadMultiple($tids);
foreach($terms as $term) {
$name = $term->getName();
$options[$term->id()] = $term->getName();
}
$default= [5];
$form['category_type'] = [
'#type' => 'checkboxes',
'#options' => $options,
'#default_value' => $default,
'#ajax' => [
'callback' => '::searchCallback',
'method' => 'replace',
'effect' => 'fade',
],
];
return $form;
}
I have tried to theme through hook_prepeocess_HOOK() but its not rendering in final my custom class.
function mytheme_preprocess_input(&$variables) {
$element = $variables['element'];
if (isset($element['#id']) && $element['#type'] == 'checkbox') {
$variables['element']['#attributes']['class'][] = 'my-custom-class';
}
}
Any help on this will be highly appreciated. Thanks in advance