form_select_options($element, $choices = NULL)
Converts an options form element into a structured array for output.
This function calls itself recursively to obtain the values for each optgroup within the list of options and when the function encounters an object with an 'options' property inside $element['#options'].
array $element: An associative array containing the following key-value pairs:
array|null $choices: (optional) Either an associative array of options in the same format as $element['#options'] above, or NULL. This parameter is only used internally and is not intended to be passed in to the initial function call.
mixed[] A structured, possibly nested, array of options and optgroups for use in a select form element.
function form_select_options($element, $choices = NULL) { if (!isset($choices)) { if (empty($element['#options'])) { return []; } $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']); // Check if the element is multiple select and no value has been selected. $empty_value = (empty($element['#value']) && !empty($element['#multiple'])); $options = []; foreach ($choices as $key => $choice) { if (is_array($choice)) { $options[] = [ 'type' => 'optgroup', 'label' => $key, 'options' => form_select_options($element, $choice), ]; } elseif (is_object($choice) && isset($choice->option)) { $options = array_merge($options, form_select_options($element, $choice->option)); } else { $option = []; $key = (string) $key; $empty_choice = $empty_value && $key == '_none'; if ($value_valid && ((!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value']))) || $empty_choice)) { $option['selected'] = TRUE; } else { $option['selected'] = FALSE; } $option['type'] = 'option'; $option['value'] = $key; $option['label'] = $choice; $options[] = $option; } } return $options; }
© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!includes!form.inc/function/form_select_options/8.1.x