Skip to main content

Views: Listing exposed taxonomy term filter options in groups

Today I needed to change the format of a taxonomy term exposed filter to display the vocabulary hierarchy in groups instead of the normal '-Item', '--Sub-Item' format (see the before and after photos below).

Before

After

The Code

To accomplish this I needed to use hook_form_alter() to change the options list. See the code below and refer to the comments for descriptions on what is going on.

  1. function hook_form_alter(&$form, $form_state, $form_id){
  2.   switch($form_id){
  3.     case 'FORM_ID':
  4.       // Create a new options array and set the first item to 'All', the wildcard operator for the view.
  5.       $new_options = array('All' => 'View All Equipment');
  6.  
  7.       // Loop through the existing options and check to see if they are an object, the default for a term hierarchy.
  8.       foreach($form['group']['#options'] as $key => $value) {
  9.       if (is_object($value)) {
  10.         // Loop through the object's option variable. Need to use a loop as the $tid's are all different.
  11.         foreach ($value->option as $tid => $title) {
  12.           // Generate an array from the term option. The format is: '-Parent', '--Child'
  13.           $count = explode('-', $title);
  14.           // Check the size of the $count array.
  15.           switch(sizeof($count)) {
  16.             case 2:
  17.               // If the array size is 2, set the $main variable and strip out the '-' from the title.
  18.               $main = str_replace('-', '', $title);
  19.               // Set this option to the new_options array.
  20.               $new_options[$main][$tid] = str_replace('-', '', $title);
  21.               break;
  22.             default:
  23.               // If the count is anything but 2, it will be a child option. Set the options accordingly.
  24.               $new_options[$main][$tid] = str_replace('-', '', $title);
  25.               break;  
  26.           }
  27.         }
  28.       }
  29.     }
  30.     // Set the $new_options array to the form options          
  31.     $form['group']['#options'] = $new_options;
  32.   }
  33. }


Comments