8 – Can’t get distinct rows from taxonomy view

Drupal 8 has a problem with creating distinct views, and the distinct views module hasn’t been ported yet. I’ve been researching this today, and haven’t found a good solution. I wrote a custom hook in a module that I ‘d hoped would fix it, but it hasn’t. I have s pretty simple content type that has a taxonomy reference, and this is an attachment that gathers the unique terms for an index.

The SQL generated for my view looks like this:

SELECT DISTINCT taxonomy_term_field_data_node__field_faq_category.name AS taxonomy_term_field_data_node__field_faq_category_name, node_field_data.nid AS nid, taxonomy_term_field_data_node__field_faq_category.tid AS taxonomy_term_field_data_node__field_faq_category_tid
{node_field_data} node_field_data
LEFT JOIN {node__field_faq_category} node__field_faq_category ON node_field_data.nid = node__field_faq_category.entity_id AND node__field_faq_category.deleted = '0'
LEFT JOIN {taxonomy_term_field_data} taxonomy_term_field_data_node__field_faq_category ON node__field_faq_category.field_faq_category_target_id = taxonomy_term_field_data_node__field_faq_category.tid
WHERE (node_field_data.type IN ('pfaq')) AND (node_field_data.status = '1')
ORDER BY taxonomy_term_field_data_node__field_faq_category_name ASC

I get a result of all rows. So I made this handler. It creates a copy of $view->result with only unique terms, then copies it back.

function wdocs_site_views_post_execute(ViewExecutable $view) {
  if (($view->id() =='faq') && ($view->current_display == 'attachment_1')) {
    $row_ids = ();
    $distinct_results = ();
    foreach ($view->result as $row) {
      $cat = $row->_entity->get('field_faq_category')->getValue();
      $tid = $cat(0)('target_id');
      if (!in_array($tid, $row_ids)) {
        $row_ids() = $row->taxonomy_term_field_data_node__field_faq_category_tid;
        $distinct_results() = $row;
    $view->result = $distinct_results;

Seems like it should do the trick, but now I’m only seeing the first two rows. A row is generated in the HTML for each value, but after the first two rows, the span.field-content is null. Looking at the returned values in my handler, they all look like they should render. As a test, I tried adding this right before the $distinct_results array is assigned to $view->result:

$distinct_results(1) = $distinct_results(2);

Still nothing displayed. However, if I assign the value of the first row to the second row, the first two rows are displayed identically:

$distinct_results(1) = $distinct_results(0);

Seems switching the data for the rows in the result should work, this has me baffled. Any suggestions on how to deal with distinct entries would be appreciated.