2

I have taxonomy terms with parent/child hierarchies (1 level deep). On a node edit page the terms are shown in a select box where I can select multiple terms.

What I'm trying to do is convert the parent terms into optgroups so they cannot get selected and the children are nicely grouped. This post shows how to structure the form array.

Basically, the array needs to get arranged like this:

$form['field_disc_topic']['und']['#options'] = array (

   'parent1' => array(
    3 => 'child1',
    4 => 'child2',
    5 => 'child3',
    ),
    26 => 'parent2' => array(
    8 => 'child1',
    9 => 'child2',
    ),
);

This is the code I started with. A parent term has depth=0, children have depth=1. I can't figure out to how build the array:

$tax = taxonomy_get_tree(2);
for ($i = 0; $i < count($tax); ++$i) {
    debug( $tax[$i]->tid);
    debug($tax[$i]->name);
    debug($tax[$i]->depth);
}

Can anyone solve this? Or is there an easier way to do this?

2 Answers 2

2
+50

Is this what you are looking for: http://drupal.org/node/76500#comment-2193734

I posted the code used in the comment. All props go to Nate Anderson from drupal.org

<?php
if (isset($form['taxonomy'][$vid])) {
  $tree = taxonomy_get_tree($vid);
  $parent = "";
  $options = array();
  foreach ($tree as $term) {
    if ($term->depth == 0) {
      $parent = $term->name;
    }
    else {
      if ($term->depth > 1) {
        $options[$parent][$term->tid] = _modulename_spaces($term->depth, '-') . ' ' . $term->name;
      }
      else {
        $options[$parent][$term->tid] = $term->name;    
      }
    }
  }
  $form['taxonomy'][$vid]['#options'] = $options;
}

function _modulename_spaces($number, $char = ' ') {
  $output = '';
  for ($i = 0; $i < $number; $i++) {
    $output .= $char;
  }

  return $output;
}
?>
1
  • brilliant, that's exactly what I needed. Thank you so much!!!
    – uwe
    Commented Nov 19, 2011 at 0:28
0

There is module for that called as optgroup select. You can try that module.

PS: I am the module maintainer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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