0

I have a module which limits the options in a views exposed filter to terms which have associated nodes. The code is based on this answer: How can I limit the exposed filters to only display values for which content exists?

Code:

if (isset($form['area-of-law']['#options'])) {

  foreach ($form['area-of-law']['#options'] as $key => $value) {

    if (is_numeric($key)) {
      $query = \Drupal::database()->select('taxonomy_index', 'ti');
      $query->fields('ti', ['nid']);
      $query->condition('ti.tid', $key);
      $nodes = $query->execute()->fetchAssoc();

      if (!$nodes) {
        unset($form['area-of-law']['#options'][$key]);
      }
    }
  }
}

This works, but all node types are returned. I would like to limit the filter further to only show those of content type X.

0
  $query = \Drupal::database()->select('taxonomy_index', 'ti');
  $query->condition('ti.tid', $key);
  $query->join('node', 'n', 'n.nid = ti.nid'); // join node table
  $query->condition('n.type', 'x'); // filter by type
  $query->fields('n', ['nid']); // add filtered nids
  $nodes = $query->execute()->fetchAssoc();
7
  • Thank you @no-sssweat. The code is working except the returned TIDs are out by one so 2, 3, 4, 5, 7 not 1, 2, 3, 4, 6. Exposed field has depth so TIDs 2, 3, 4 and 6 are children of 1… could this be causing the issue? – QuietSpecialist Aug 17 '20 at 15:01
  • Sorry not on my PC, try moving the join line before first condition and if still same try changing fields to ti instead of n. – No Sssweat Aug 17 '20 at 15:22
  • Still not working, unfortunately. – QuietSpecialist Aug 18 '20 at 10:57
  • TIDs are out by one You mean NIDs, you're retrieving NIDs. Are you sure the Node IDs you're getting back do not belong to content type X? – No Sssweat Aug 18 '20 at 12:38
  • Your code is filtering the exposed filter list to only show terms that have associated nodes however, the list option values (TIDs) are out by one. Screenshot here: digitaldots.co.uk/exposed-filter-options.png – the values should be 2, 3, 4, 6. – QuietSpecialist Aug 18 '20 at 13:00

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.