Drupal - How can I disable a single checkbox in a 'checkboxes' FAPI element?

A clean way does exist in Drupal 7! Apparently, per this post, it's not yet documented.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['checkboxes_element']['#disabled'] = TRUE; //disables all options
  $form['checkboxes_element'][abc]['#disabled'] = TRUE; //disables option, called abc
}

Another example.

You can also set #access function to FALSE, to completely hide the checkbox.


Unfortunately there's no really clean way to do that in FAPI. Your best bet -- if you're determined -- is to alter an additional #process function onto the checkboxes element.

The default function added to elements of type 'checkboxes' is actually a function (expand_checkboxes()) splits the single element out into multiple elements of type 'checkbox' that are later merged back into one. If you were to piggyback your second process function, it could reach into the expanded group of 'checkbox' elements and disable the one in question.

The following code is utterly untested, so caveat emptor:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['checkboxes_element']['#process'][] = 'mymodule_disable_element';
}

function mymodule_disable_element($element) {
  foreach (element_children($element) as $key) {
    if ($key == YOUR_CHECK_VALUE) {
      $element[$key]['#disabled'] = TRUE;
      return;
    }
  }
}

Here is my code for Drupal 7, to change the Roles element in the Edit User page.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['checkboxes_element']['#pre_render'][] = 'form_process_checkboxes'; // I had to add this one, or it will return the first role only with my callback bellow
  $form['checkboxes_element']['#pre_render'][] = 'mymodule_disable_element';
}

function mymodule_disable_element(($element) {
  foreach (element_children($element) as $key) {
    if ($key == YOUR_CHECK_VALUE) {
      $element[$key]['#attributes']['disabled'] = 'disabled';
    }
  }
  return $element;
}

Tags:

Forms

7