Problem/Motivation
Create a view with a multi-valued field that is display multiple values in the same row, then add a filter or sort on that multi-valued field, or a field on an entity that is related via that multi-valued field, then duplicate rows will show in the results.
Steps to reproduce
- Create a content type that has a multi-valued field. Example: A taxonomy vocabulary, where each term has a multi-valued User field, such as "Working Group" with the field "Group Members".
- Create a few entities of the content type, some having multiple values for that field.
- Create a view for that content type. (Working Groups).
- Add the multi-valued field to the view. (Group Members)
- Add the a relationship based on that multi-valued field. (field_group_members: User)
- Add a sort to the view for a field on the related entity, such as "User: Last Name (ASC)"
- Instead of seeing one row for each Working Group, you should see one row per group for each person in the group. Each row shows all the group members.
Proposed resolution
Don't show duplicate rows when the multi-valued field is contained in a single row, while still allowing filtering and sorting on those rows.
Workaround
This workaround removed the duplicate rows, but the number of rows displayed on a page might be less than the configured setting, as each deleted row still took up a "slot" on the page when the query was run.
/**
* Implements hook_views_pre_render().
*/
function my_module_views_pre_render(ViewExecutable $view): void {
switch ($view->id()) {
case 'my_view_id':
// Ensure there's only one row per group.
// See https://www.drupal.org/project/drupal/issues/2721691
$combined = [];
foreach ($view->result as $row) {
if (!isset($combined[$row->_entity->id()])) {
$combined[$row->_entity->id()] = $row;
}
}
// Replace the result set with the combined result.
$view->result = $combined;
$view->total_rows = count($combined);
break;
}
}
Remaining tasks
User interface changes
API changes
Data model changes
Release notes snippet
Original issue
I have a multivalued date field on a content type, and a view showing all published items of that content type. Adding an exposed sort by field_date to the view creates duplicate rows for content items which have multiple values in the date field.
Desired behavior: Adding a sort on a multivalue field on a view should expose additional options for how to sort that field, or should default to the first field item.