0

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

0

I think the Form Options Attribute module will solve this for you. It allows you to add option attributes in the form element render array. Below is the example from the module page. It also supports checkboxes as well.

$form['states'] = array(
  '#type' => 'select',
  '#title' => t('States'),
  '#options' => array(
    'AL' => t('Alabama'),
    'AK' => t('Alaska'),
    'AZ' => t('Arizona'),
    'AR' => t('Arkansas'),
    // ..
    'WI' => t('Wisconsin'),
    'WY' => t('Wyoming'),
  ),
  '#options_attributes' => array(
    'AL' => array('class' => array('southeast'), 'data-bbq-meat' => 'pork'),
    'AK' => array('class' => array('non-contiguous'), 'data-bbq-meat' => 'salmon'),
    'AZ' => array('class' => array('southwest'), 'data-bbq-meat' => 'rattlesnake'),
    'AR' => array('class' => array('south'), 'data-bbq-meat' => 'beef'),
    // ...
    'WI' => array('class' => array('midwest'), 'data-bbq-meat' => 'cheese'),
    'WY' => array('class' => array('flyover'), 'data-bbq-meat' => 'bison'),
    ),
  '#attributes' => array('class' => array('states-bbq-selector')),
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.