New EntityReference filter for Drupal Views

Drupal 11.1 was released yesterday, and one of the most important things in this release is the addition of a new EntityReference filter for Views.

Before this version, if you wanted to add an exposed filter to an entity reference field — in my case, as shown in the image below, it's the field_related_articles field — the filter would be a simple text input field.

Image

Now, it can be a select box or an autocomplete field, as shown in the second image.

Image

What I don't like is that this filter isn't used by default; instead, you need to write a hook_views_data_alter() for that. In my example, it would look like this:

/**
* Implements hook_views_data_alter().
*/
function MY_MODULE_views_data_alter(array &$data): void {
  $field_name = 'field_related_articles';
  $data['node__' . $field_name][$field_name . '_target_id']['filter']['id'] = 'entity_reference';
}

Read more in the change record.

About the Author

Goran Nikolovski is a senior developer with over 10 years of experience in web, app, and AI solutions. He founded this website to share his expertise, provide useful resources, and contribute to the broader developer community.

AI Assistant