Sorting Accented Characters in Select Options

Created on 16 April 2025, 11 days ago

Problem/Motivation

When using VERF in a view to display a select with options, the default sorting mechanism (natcasesort()) used in the getValueOptions() method doesn't properly handle accented characters. As a result, entities with names containing accented characters (like é, è, ê, etc.) are not sorted correctly with their non-accented counterparts in alphabetical order. This causes usability issues for sites with multilingual content or content in languages that use accented characters.

Steps to reproduce

  1. Create a content type with an entity reference field. (e.g., A node "Ressource" referencing a node "Author")
  2. Create several entities with names that contain accented characters (e.g., Author's name)
  3. Create a view using previous references as an exposed filter (e.g., A "Ressource" that you can filter based on the author's name)
  4. Observe that in the dropdown list, accented characters are not sorted correctly with their non-accented equivalents

Current sorting output example:

[...]
Elsa
Emilian
Emilie
Emmanuel
Emmanuelle
Emmy
Erica
Eric
[...]
Yves
Zeynab
Zhi
Élise
Éloïse
Éléonore
Émile
Émilie
Éric

Notice how 'Élise', 'Émilie' and 'Éric' appear after 'Zhi' instead of being grouped with their non-accented counterparts 'Elsa', 'Emilie' and 'Eric'.

Proposed resolution

Replace the natcasesort() function with PHP's Collator class from the Intl extension, which provides locale-aware string comparison. This allows for proper handling of accented characters in sorting.

// Get the current locale
$locale = $this->languageManager->getCurrentLanguage()->getId();

// Sort with proper collation
if (class_exists('Collator')) {
  $collator = new \Collator($locale);
  $collator->setStrength(\Collator::SECONDARY);
  $collator->asort($this->valueOptions);
}
else {
  // Fallback to natcasesort if Collator is not available
  natcasesort($this->valueOptions);
}

Expected result with proper collation:

[...]
Elsa
Élise
Éléonore
Éloïse
Emilian
Emilie
Émile
Émilie
Emmanuel
Emmanuelle
Emmy
Erica
Eric
Éric
[...]
Yves
Zeynab
Zhi

🐛 Bug report
Status

Active

Version

2.1

Component

Code

Created by

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

Merge Requests

Comments & Activities

Production build 0.71.5 2024