Provide additional options for sorting the options in Select form elements

Created on 24 July 2019, almost 6 years ago
Updated 18 August 2023, almost 2 years ago

Problem/Motivation

In #3065903: Add label sort ability to Select element , we add two options to the select form element:

  • #sort_options: Set to TRUE (default is FALSE) to sort the options by their (translated) labels.
  • #sort_start: Set to an integer (default is 0) to start the sorting at that index in the labels. For instance, if your first option is "- none -", start the sorting at index 1 to make sure that first option stays at the top of the list of options.

We propose adding additional, related options. Two such options were suggested in comments on that issue.

Proposed resolution

Add related options:

  1. #sort_direction: Set to 'ASC' (default) for ascending order, 'DESC' for descending order.
  2. #sort_natural: Set to FALSE (default) to sort using strcmp(), TRUE to sort using strnatcmp().
  3. #sort_end: Integer for number of elements at the end to leave at the end, or maybe the element number to stop sorting at (TBD which is best -- probably easiest to say "leave 1 element at the end" which is the usual use case.
  4. #sort_unique: Set to TRUE (default is FALSE) to remove duplicates after sorting. Two options are considered duplicates if they have the same value attribute and text value (label). This option could be used in #3089528: Sort options for entity reference fields can be ambiguous if a field has different labels across bundles .

See Natural sort order (Wikipedia) and strnatcmp (PHP docs) for the differences between strcmp() and strnatcmp().

Remaining tasks

Decide whether these options are useful enough that they should be added to Drupal core. (There is already some discussion of this question on #3065903: Add label sort ability to Select element .)

Decide whether to change the names and/or allowed values of these options. For example, if there are useful comparison functions other than strcmp() and strnatcmp(), then we might replace the boolean sort_natural option with a string-valued option.

Decide whether there are other related options worth adding.

Decide whether there are other places in core where strnatcmp() is a useful alternative.

User interface changes

None.

API changes

New options will be added to the select element in the Form API.

Data model changes

None.

Release notes snippet

TODO.

Feature request
Status

Active

Version

11.0 🔥

Component
Form 

Last updated about 9 hours ago

Created by

🇺🇸United States benjifisher Boston area

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024