Tag Archives: Checkboxes

Adding even and odd classes to checkboxes in Drupal 7

While theming a page for a client, I came across an interesting challenge: adding even and odd classes to checkboxes. Normally I would have gone with javascript or CSS3 (:nth-child), but I wondered if it can be achieved in ‘the Drupal way’ and achieve the best cross browser support. Google didn’t turn up any results so I decided to do a quick exercise on form element theming. Here’s how I got it to work.

Add our own checkboxes processor. See hook_element_info_alter.

function MYTEMPLATE_element_info_alter(&$type){
  // Append our processor
  $type['checkboxes']['#process'][] = 'MYTEMPLATE_process_checkboxes';
}

Implement the customer checkboxes processor to add the classes we want. See form_process_checkboxes

function MYTEMPLATE_process_checkboxes($element){
  // Loop through options to add striping class and attribute
  if (count($element['#options']) > 0) {
    $i = 0;
    foreach ($element['#options'] as $key => $choice) {
      $element[$key]['#attributes']['class'][] = ($i % 2 == 0) ? 'odd' : 'even';
      $i++;
    }
  }
  return $element;
}

I quickly realized that while this added the even and odd classes on the <input> elements, it would be easier for the themer to have it on the form element wrapper as well. So I decided to add a ‘striping’ key to ‘#attributes’ so that I can identify it in the form element wrapper.

The new processor:

function MYTEMPLATE_process_checkboxes($element){
  // Loop through options to add striping class and attribute
  if (count($element['#options']) > 0) {
    $i = 0;
    foreach ($element['#options'] as $key => $choice) {
      $element[$key]['#attributes']['class'][] = ($i % 2 == 0) ? 'odd' : 'even';
      $element[$key]['#attributes']['striping'] = ($i % 2 == 0) ? 'odd' : 'even';
      $i++;
    }
  }
  return $element;
}

Next, modify the template_form_element() to add the classes on the form element wrapper.

function MYTEMPLATE_form_element($variables) {
  ...
  if (!empty($element['#attributes']['striping'])) {
    $attributes['class'][] = $element['#attributes']['striping'];
  }
  $output = '<div' . drupal_attributes($attributes) . '>' . "\n";
  ...
}

Clear the class registry and we are done. This is by no means the best method available, but is definitely the most straightforward way that jumped at me. If you have a more efficient way do share in the comments.