Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UHF-9953: Sort the autocomplete result by title length. #296

Merged
merged 1 commit into from
Apr 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ use Drupal\editor\Entity\Editor;
use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;
use Drupal\media\Entity\Media;
use \Drupal\Core\Entity\RevisionLogInterface;
use Drupal\Core\Database\Query\AlterableInterface;
use Drupal\Core\Entity\RevisionLogInterface;

/**
* Implements hook_cron().
Expand Down Expand Up @@ -601,3 +602,43 @@ function infofinland_common_elasticsearch_connector_load_library_options_alter(&
function infofinland_common_preprocess_html(&$variables) {
$variables['attributes']['class'][] = 'infofinland-admin';
}

/**
* Implements hook_query_TAG_alter().
*
* Orders entity reference query by length so autocomplete shows the exact match at the top.
*
* @see https://www.drupal.org/project/drupal/issues/3304175
* @see \Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection::buildEntityQuery()
*/
function infofinland_common_query_entity_reference_alter(AlterableInterface $query): void {
if (!$query->hasAllTags('entity_query', 'entity_query_node')) {
return;
}

$title_field = 'node_field_data.title';
$conditions = $query->conditions();

if (empty($conditions) || !isset($conditions[0]['field'])) {
return;
}

$has_title = false;
foreach ($conditions as $condition) {
if (is_array($condition) && $condition['field'] === $title_field) {
$has_title = true;
}
}

if (!$has_title) {
return;
}

$query->addExpression("LENGTH($title_field)", 'title_length');
$query->orderBy('title_length');

// Prevent a mysql error.
if (!empty($query->getGroupBy())) {
$query->groupBy('title_length');
}
}