3

How to remove duplicate results from views block ? I have tried aggregation method and query distint but none of them working.

As previously i did the same by using the below code, but how to use the same code in drupal 8 ?

  function bootstrap_views_pre_render(&$view) {
      $used_nids = array();
       $new_view_result = array();

   if ($view->name == 'view_name') {
foreach ($view->result as $row) {
    if (!in_array($row->nid, $used_nids)) {
      $new_view_result[] = $row;
      $used_nids[] = $row->nid;
    }
}

$view->result = $new_view_result;
 }
  }

Is there any other possible solution of my problem ?

7

For anyone else looking for a Drupal 8 solution for Views Distinct, I was able to get this to work by creating a custom module with MY_MODULE.views_execution.inc file with this code:

<?php

use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_render().
 */
function MY_MODULE_views_pre_render(Drupal\views\ViewExecutable $view) {
  $unique_uuids = $new_view_result = [];
  $new_row_index = 0;

  // Loop through results and filter out duplicate results.
  foreach ($view->result as $row) {
    // Use UUID so this works for all entities
    $uuid = $row->_entity->uuid();

    if (!in_array($uuid, $unique_uuids)) {
      $row->index = $new_row_index;
      $new_view_result[] = $row;
      $unique_uuids[] = $uuid;
      $new_row_index++;
    }
  }

  // Replace $view->result with new array. Apparently views requires sequentially keyed
  // array of results instead of skipping keys (e.g. 0, 2, 4, etc), so we can't just
  // unset the duplicates.
  $view->result = $new_view_result;

  // Update the view index to match the new number of rows.
  $view->total_rows = $new_row_index;
}
3
  • it isn't working
    – Ali Nouman
    Sep 20 '18 at 12:31
  • simple to install and works for me
    – ankles
    Feb 5 '19 at 11:44
  • 4
    This is not the right way to do things as it removes results. The fix should be done at the query level, prior to returning results. If a user requests 10 items and 3 are duplicates, they will get back 7 results, instead of 10 non-duplicates.
    – atwixtor
    Jul 19 '19 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy