You are here

function cshs_form_select_options in Client-side Hierarchical Select 7

Modified version of form_select_options.

Adds a data-parent attribute for the term options.

1 call to cshs_form_select_options()
theme_cshs_select in ./cshs.module
Theme function to render the select.

File

./cshs.module, line 240
A simple clientside hierarchical select widget for taxonomy terms.

Code

function cshs_form_select_options($element, $choices = NULL) {
  if (!isset($choices)) {
    $choices = $element['#options'];
  }

  // array_key_exists() accommodates the rare event where $element['#value'] is
  // NULL.
  // isset() fails in this situation.
  $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
  $value_is_array = $value_valid && is_array($element['#value']);
  $options = '';
  foreach ($choices as $key => $choice) {
    $key = (string) $key;
    if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || $value_is_array && in_array($key, $element['#value']))) {
      $selected = ' selected="selected"';
    }
    else {
      $selected = '';
    }

    // Don't proccess element if no array. For required fields Drupal add such a
    // flat option.
    if (!is_array($choice)) {
      continue;
    }

    // Get the name of the term.
    $term_name = $choice['name'];

    // Get the tid of the parent.
    $parent_tid = $choice['parent_tid'];

    // If widget is used as field widget, so lets see if there is a root configured.
    if (isset($element['#field_name'])) {
      $field_instance_info = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);
      if (isset($field_instance_info['widget']['settings']['cshs']['parent'])) {
        $root_tid = $field_instance_info['widget']['settings']['cshs']['parent'];

        // If the parent term is actually the configured root of this field, set
        // parent to 0.
        if ($parent_tid == $root_tid) {
          $parent_tid = 0;
        }
      }
    }

    // Prepare data-parent attribute.
    $data_parent = ' data-parent="' . $parent_tid . '" ';
    $options .= '<option value="' . check_plain($key) . '"' . $selected . $data_parent . '>' . check_plain($term_name) . '</option>';
  }
  return $options;
}