Search code examples
drupaldrupal-7drupal-viewsdrupal-taxonomy

Views hierarchical taxonomy select box


I'm trying to create a Drupal web for a travel agency and need your help.

  • I store locations in a taxonomy with hierarchy, the structure looks like this:

    • Europe
      • France
        • Paris
      • Germany
        • Berlin
  • I'm using a view with "Has taxonomy terms (with depth)" filter, exposed as a selectbox.

  • "Show hierarchy in dropdown" is enabled

It works fine, but the selectbox starts to get pretty huge as the number of the location is increasing.

So my question is: Is it possible to show just the 1st and 2nd level of the taxonomy in the select box? Or is it possible to show each level of the taxonomy in a separate select box?

Thank you!


Solution

  • Use hierarchical select module to create select list. This will give you a hierarchy with '-' symbol in front all child elements. Then you can alter the form with hook_form_alter function.

    function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
     if (($form_id == 'your_form_id')) {
      foreach ($form['tid']['#options'] as $term_key => $term) {
          // Check if this is a child by looking for '-' as first char in string
          $term_value = reset($term->option);
          if($term_value[0] == '-') {
            unset($form['tid']['#options'][$term_key]);
          }
        }
      }
    }