How to create optgroups from taxonomy terms? 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' =&gt; array(
    3 =&gt; 'child1',
    4 =&gt; 'child2',
    5 =&gt; 'child3',
    ),
    26 =&gt; 'parent2' =&gt; array(
    8 =&gt; 'child1',
    9 =&gt; '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 &lt; count($tax); ++$i) {
    debug( $tax[$i]-&gt;tid);
    debug($tax[$i]-&gt;name);
    debug($tax[$i]-&gt;depth);
}


Can anyone solve this? Or is there an easier way to do this?
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

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

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

  return $output;
}
?&gt;