6

Now I'm having like

1|City name
2|Another city name
3|Little town name

in values field when creating content type field

How can I wrap some of them in a group that will appear as “optgroup” in html generated?

13

you can use a hook_FORM_ID_alter and then add code like this:

$form['FIELDNAME']['#options'] = array (

   'parent1' => array(
      3 => 'child1',
      4 => 'child2',
      5 => 'child3',
    ),
    'parent2' => array(
      8 => 'child1',
      9 => 'child2',
    ),
);
  • How can I also add the #multiple parameter to a select element when using optgroups. When I try it my select box turns to a series of checkboxes with with the title array(). I have tried adding multiple as an attribute but then drupal does not recognise any of the selections and rejects the form as though I had failed to select an option. – PrestonDocks May 4 '14 at 15:31
5

using forms api inside hook_form-alter function you can generate parent-child array then drupal_render will render dropdown.

    <? 
function mymodule_form_alter(&$form, &$form_state, $form_id) {     

    if ($form['#form_id'] == 'my_nodetype_node_form') {    
    $parents = taxonomy_get_tree($vid = 2 /*vocaulary ID*/, $parent = 0, $max_depth = 1);

    foreach ($parents as $term) {
      $options[$term->name] = array();
      $children = taxonomy_get_tree($term->vid, $term->tid);

      foreach ($children as $child) {
        $options[$term->name][$child->tid] = $child->name;
      }
    }
    //echo '<pre>';print_r($options);die;
    $form['the_taxonomy_terms_field']['und']['#options'] = $options;
    }
}
?>
  • Thanks Clive. Saved me 1/2 hours work! May I confess, just caught myself copy pasting one of your answers yet again to close a task. PS: I did work a little by posting this comment ... and obviously changing the form_id and field name of term reference ... and swapped $vid variable for a constant in the function call to taxonomy_get_tree as this vocab is used in other places for nodequeue interaction and such. But heck, you still did most the work!!! Thanks friend. ;) – stefgosselin Dec 19 '13 at 5:12
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, privacy policy and cookie policy

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