Skip to content

Instantly share code, notes, and snippets.

@mattschaff
Created April 3, 2019 14:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mattschaff/2309edca2d865b9b06c0bb6bd8038402 to your computer and use it in GitHub Desktop.
Save mattschaff/2309edca2d865b9b06c0bb6bd8038402 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