Would you like to be notified for every new articles? Please click HERE to subscribe for newsletter.

Modify Entity Reference Autocomplete Result In Drupal 8

  • Posted on: 2 July 2017
  • By: admin

In some cases we might need to modify the autocomplete result in Drupal 8. For example, when editing a node, in content authoring section, there is an autocomplete textfield for entering the author for the content. By default, all users will be available in the autocomplete list, but there might be a case when we need to exclude the blocked user from the list. Fortunately, we are able to do that by using one hook function called hook_query_alter. It's a very useful hook which allow us to modify some query objects such as adding a new filter condition, joining to other table, etc.

The following code will modify the autocomplete result of user entity reference field. The users available in the autocomplete list will exclude the blocked users. Please note that, to choose a specific query to be altered, we must check its tag so we won't break the unintended query.


<?php
/**
 * Implements hook_query_alter().
 */
function my_module_query_alter($query) {
  
// Users autocomplete has the tag "user_access".
  //
  // Entity autocomplete is generated in:
  //   Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection
  // function:
  //   buildEntityQuery()
  //
  // See the file:
  //   lib/core/Drupal/Core/Entity/Plugin/EntityReferenceSelection/DefaultSelection.php
  //
  
if ($query->hasTag('user_access')) { // Check the tag
    // We only display the active ones (exclude the blocked ones).
    
$query->condition('users_field_data.status'1);
  }
}
?>
Tags: 

Add new comment

Limited HTML

  • Allowed HTML tags: <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.