Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jcicero518/fd7291dfcc844ddd4bca8ad9ea7994c8 to your computer and use it in GitHub Desktop.
Save jcicero518/fd7291dfcc844ddd4bca8ad9ea7994c8 to your computer and use it in GitHub Desktop.
Drupal 8: Remove duplicate records in view
<?php
/**
* Implements hook_preprocess_views_view
*/
function my_module_preprocess_views_view(&$vars){
// Only use unique IDs for view.
// Use this code for views with Better Exposed Filters.
if ($vars['view']->id() === 'view_name_bef') {
$rows = [];
if (isset($vars['rows']['output'][0])) {
$rows = $vars['rows']['output'][0]['#rows'];
}
$new_rows = [];
$used_nids = [];
if (is_array($rows)) {
foreach ($rows as $row){
$nid = $row['#row']->node_field_data_nid; // Change to the field you want to be unique.
if (!in_array($nid, $used_nids)) {
$used_nids[] = $nid;
$new_rows[] = $row;
}
}
$vars['rows']['output'][0]['#rows'] = $new_rows;
}
}
// Use this code for views without Better Exposed Filters.
if ($vars['view']->id() === 'view_name_no_bef') {
$rows = $vars['rows'][0]['#rows'];
$new_rows = [];
$used_nids = [];
foreach ($rows as $row){
$nid = $row['#row']->node_field_data_nid; // Change to the field you want to be unique.
if (!in_array($nid, $used_nids)) {
$used_service_tids[] = $nid;
$new_rows[] = $row;
}
}
$vars['rows'][0]['#rows'] = $new_rows;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment