Created
February 11, 2020 22:58
-
-
Save MogulChris/71137a6f7e11b5ee826423d64e75d631 to your computer and use it in GitHub Desktop.
Optgroups in Drupal 7 select fields with the Form API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Wow I don't miss working on Drupal. Anyway, I needed to do so recently and this took a little Googling to figure out. | |
//Drupal 7 select fields can have optgroups if you make their options an array of arrays, keyed by the optgroup names | |
function mymodule_form_alter(&$form, &$form_state, $form_id){ | |
//assuming we are trying to alter the form of a custom node type called event | |
if ($form_id == 'event_node_form') { | |
$optgroup_options = array( | |
'Optgroup one' => array(123 => 'First value', 456 => 'Second value'), | |
'Optgroup two' => array(456 => 'Third value', 789 => 'Fourth value'), | |
); | |
//assume the field we are altering is called 'country' and is a select field | |
$form['field_country']['und']['#options'] = $optgroup_options; | |
} | |
}//mymodule_form_alter() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment