Disable options in a form select list

Public

Select lists are hard to figure out how to modify if they've been provided by a different part of Drupal. This example is pulled from the ELMS CLE distribution where it sees a list of items in a views select filter, then changes the title to be -"nodetitle (Private)" if a field on the assignment is marked private. If value is set to an array Drupal will disable the field.

Get raw version
php
  1. /**
  2.  * Implementation of hook_form_FORM_ID_alter().
  3.  */
  4. function cle_helper_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  5. // look for the cle submissions views
  6. if (strpos($form['#id'], 'cle-submissions-page') && isset($form['field_assignment_target_id'])) {
  7. // pull out the options so we can set new ones
  8. $options = $form['field_assignment_target_id']['#options'];
  9. $newoptions = array('All' => t('- Any -'));
  10. // load the related entities
  11. $assignments = entity_load('node', array_keys($options));
  12. // loop through assignment entities to assemble
  13. foreach ($assignments as $assignment) {
  14. $disabled = FALSE;
  15. $name = $assignment->title;
  16. // see if it is a private submission
  17. if ($assignment->field_visibility['und'][0]['value'] == 0) {
  18. $name .= '(' . t('Private') . ')';
  19. $disabled = TRUE;
  20. }
  21. // if it should be disabled then keep it in the list but disable it
  22. if ($disabled) {
  23. $key = $name;
  24. $value = array();
  25. }
  26. else {
  27. $key = $assignment->nid;
  28. $value = check_plain($name);
  29. }
  30. // append our modified (potentially) output to the options
  31. $newoptions[$key] = $value;
  32. }
  33. $form['field_assignment_target_id']['#options'] = $newoptions;
  34. }
  35. }