You are here

public function FilterWidgetBase::processSortedOptions in Better Exposed Filters 8.4

Same name and namespace in other branches
  1. 8.5 src/Plugin/better_exposed_filters/filter/FilterWidgetBase.php \Drupal\better_exposed_filters\Plugin\better_exposed_filters\filter\FilterWidgetBase::processSortedOptions()

Sorts the options for a given form element alphabetically.

Parameters

array $element: The form element.

\Drupal\Core\Form\FormStateInterface $form_state: Form state.

Return value

array The altered element.

File

src/Plugin/better_exposed_filters/filter/FilterWidgetBase.php, line 271

Class

FilterWidgetBase
Base class for Better exposed filters widget plugins.

Namespace

Drupal\better_exposed_filters\Plugin\better_exposed_filters\filter

Code

public function processSortedOptions(array $element, FormStateInterface $form_state) {
  $options =& $element['#options'];

  // Ensure "- Any -" value does not get sorted.
  $any_option = FALSE;
  if (empty($element['#required'])) {

    // We use array_slice to preserve they keys needed to determine the value
    // when using a filter (e.g. taxonomy terms).
    $any_option = array_slice($options, 0, 1, TRUE);

    // Array_slice does not modify the existing array, we need to remove the
    // option manually.
    unset($options[key($any_option)]);
  }

  // Not all option arrays will have simple data types. We perform a custom
  // sort in case users want to sort more complex fields (e.g taxonomy terms).
  if (!empty($element['#nested'])) {
    $delimiter = $element['#nested_delimiter'] ?? '-';
    $options = BetterExposedFiltersHelper::sortNestedOptions($options, $delimiter);
  }
  else {
    $options = BetterExposedFiltersHelper::sortOptions($options);
  }

  // Restore the "- Any -" value at the first position.
  if ($any_option) {
    $options = $any_option + $options;
  }
  return $element;
}