By elber on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
10.3.x
Introduced in version:
10.3.0
Issue links:
Description:
Four new hooks are available for altering an EntityQuery.
In core they are implemented for config entities, and content entities using sql storage.
- hook_entity_query_alter(\Drupal\Core\Entity\Query\QueryInterface $query)
Alter any entity query. - hook_entity_query_ENTITY_TYPE_alter(\Drupal\Core\Entity\Query\QueryInterface $query)
Alter entity queries for a specific entity type. - hook_entity_query_tag__TAG_alter(\Drupal\Core\Entity\Query\QueryInterface $query)
Alter entity queries that have a specific tag. - hook_entity_query_tag__ENTITY_TYPE__TAG_alter(\Drupal\Core\Entity\Query\QueryInterface $query)
Alter entity queries for a specific entity type that have a specific tag.
Note the double underscores to avoid potential hook collisions for hook_entity_query_tag implementations.
Examples
hook_entity_query_alter(\Drupal\Core\Entity\Query\QueryInterface $query)
function hook_entity_query_alter(\Drupal\Core\Entity\Query\QueryInterface $query) {
$entityType = \Drupal::entityTypeManager()->getDefinition($query->getEntityTypeId());
$query->sort($entityType->getKey('id'), 'desc');
}
This alters every entity query to sort the results by the 'id' key in descending order.
hook_entity_query_ENTITY_TYPE_alter(\Drupal\Core\Entity\Query\QueryInterface $query)
function hook_entity_query_user_alter(\Drupal\Core\Entity\Query\QueryInterface $query) {
$query->condition('uid', '1', '<>');
}
Exclude user 1 from any user entity query.
hook_entity_query_tag__TAG_alter(\Drupal\Core\Entity\Query\QueryInterface $query)
function hook_entity_query_tag__entity_reference_alter(\Drupal\Core\Entity\Query\QueryInterface $query) {
$entityType = \Drupal::entityTypeManager()->getDefinition($query->getEntityTypeId());
if ($entityType->getKey('label')) {
$query->sort($entityType->getKey('label'));
}
}
Sorts any entity reference query by the entity label.
hook_entity_query_tag__ENTITY_TYPE__TAG_alter(\Drupal\Core\Entity\Query\QueryInterface $query)
function hook_entity_query_tag__user__entity_reference_alter(\Drupal\Core\Entity\Query\QueryInterface $query) {
$query->condition('uid', '1', '<>');
}
Exclude user 1 from user entity reference queries.
Impacts:
Module developers