Views: Listing exposed taxonomy term filter options in groups

Profile picture for user Phil Frilling
By Phil Frilling, 20 April, 2012
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.

function hook_form_alter(&$form, $form_state, $form_id){
  switch($form_id){
    case 'FORM_ID':
      // Create a new options array and set the first item to 'All', the wildcard operator for the view.
      $new_options = array('All' => 'View All Equipment');
      
      // Loop through the existing options and check to see if they are an object, the default for a term hierarchy.
      foreach($form['group']['#options'] as $key => $value) {
      if (is_object($value)) {
        // Loop through the object's option variable. Need to use a loop as the $tid's are all different.
        foreach ($value->option as $tid => $title) {
          // Generate an array from the term option. The format is: '-Parent', '--Child'
          $count = explode('-', $title);
          // Check the size of the $count array.
          switch(sizeof($count)) {
            case 2:
              // If the array size is 2, set the $main variable and strip out the '-' from the title.
              $main = str_replace('-', '', $title);
              // Set this option to the new_options array.
              $new_options[$main][$tid] = str_replace('-', '', $title);
              break;
            default:
              // If the count is anything but 2, it will be a child option. Set the options accordingly.
              $new_options[$main][$tid] = str_replace('-', '', $title);
              break;  
          }
        }
      }
    }
    // Set the $new_options array to the form options          
    $form['group']['#options'] = $new_options;
  }
}