You are here

public static function Multiselect::getOptions in Multiselect 8

Same name and namespace in other branches
  1. 2.x src/Element/Multiselect.php \Drupal\multiselect\Element\Multiselect::getOptions()

Helper function for get multiselect options.

Parameters

string $type: The type of options.

array $element: An associative array containing the properties of the element.

mixed $choices: Mixed: Either an associative array of items to list as choices, or an object with an 'option' member that is an associative array. This parameter is only used internally and should not be passed.

Return value

array An array of options for the multiselect form element.

1 call to Multiselect::getOptions()
template_preprocess_multiselect in ./multiselect.module
Prepares variables for multiselect element templates.

File

src/Element/Multiselect.php, line 52

Class

Multiselect
Provides a form element for displaying the label for a form element.

Namespace

Drupal\multiselect\Element

Code

public static function getOptions($type, array $element, $choices = NULL) {
  if (!isset($choices)) {
    if (empty($element['#options'])) {
      return [];
    }
    $choices = $element['#options'];
  }
  $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']);
  foreach ($choices as $key => $choice) {
    if (is_array($choice)) {

      // @todo add support for optgroup.
      $options[] .= self::getOptions($type, $element, $choice);
    }
    elseif (is_object($choice) && isset($choice->option)) {
      $options[] .= self::getOptions($type, $element, $choice->option);
    }
    else {
      $key = (string) $key;
      $empty_choice = $empty_value && $key == '_none';
      switch ($type) {
        case 'available':
          if (!($value_valid && (!$value_is_array && (string) $element['#value'] === $key || $value_is_array && in_array($key, $element['#value']) || $empty_choice))) {
            $options[] = [
              'type' => 'option',
              'value' => $key,
              'label' => $choice,
            ];
          }
          break;
        case 'selected':
          if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || $value_is_array && in_array($key, $element['#value']) || $empty_choice)) {
            $options[] = [
              'type' => 'option',
              'value' => $key,
              'label' => $choice,
            ];
          }
          break;
      }
    }
  }
  return $options;
}