Filter empty exposed links

Public

Hey ho everybody and thank you for viewing my code Snipp.

With this code you will able to remove empty exposed links.

Get raw version
php
  1. /**
  2.  * Implements hook_form_FORM_ID_alter().
  3.  */
  4. function hook_form_views_exposed_form_alter(&$form, $form_state) {
  5.  
  6. // Define important Variables
  7. $identifier = 'cat';
  8. global $language;
  9.  
  10.  
  11. // prevent recursion - only execute once
  12. static $called = 0;
  13.  
  14. if ($called === $form['#id']) {
  15. return;
  16. }
  17.  
  18. $called = $form['#id']; // flag as called
  19.  
  20.  
  21. // Now we're checking each identifier on options
  22. $tids = array();
  23. foreach ($form[$identifier]['#options'] as $key => $option) {
  24. if ($key != 'All') {
  25.  
  26. $tids[$key]['tid'] = $key;
  27.  
  28. // Checking if there is a entry it this tid in taxonomy_index
  29. // Joining the node table so we can check on language.
  30. $query = db_select('taxonomy_index', 't');
  31.  
  32. $query ->join('node', 'n', 't.nid = n.nid');
  33.  
  34. $query ->fields('t')
  35. ->fields('n')
  36. ->condition('t.tid', $key, '=')
  37. ->condition('n.language', $language->language, '=')
  38. ->condition('n.status', 1, '=');
  39. $result = $query->execute();
  40.  
  41. $tids[$key]['count'] = $result->rowCount();
  42.  
  43. // Removing the option without entrys
  44. if($tids[$key]['count'] == 0){
  45. unset($form[$identifier]['#options'][$key]);
  46. }
  47. }
  48. }
  49. }