I'm creating form using drupal_get_form and I'm using the following code for creating a select list:

$form['select-user-group'] = array(
  '#type' => 'select',
  '#title' => t('Select a group'),
  '#options' => array(
    '' => t('-- Select a user group --'),        
  '#ajax' => array(
  'event' => 'load',
  'callback' => 'selectuser_ajax_callback',
  'method' => 'replace',

and then I'm trying to define a function like following to dynamically add options to the select list:

function selectuser_ajax_callback() {


  $result = db_query("select * from {content_type_usergroup}");
  $record = db_fetch_object($result);

  $str = '<select>';
  while ($obj = db_fetch_object($result)) {
    $str .= '<option value=' + $obj->vid + '>' + $obj->field_p_group_name_value + '</option>';
  $str .= '</select>';

  echo $str;

But it's not working. How to make this function work properly to populate the select list '#options?

  • 1
    <select> in while loop will load <select> for every record.You should remove it from while loop Commented Jul 15, 2015 at 10:18

1 Answer 1


For just populating select list options, you don't need to go through an Ajax approach! Simply write a separate function and write your database query inside it and then just call that function in '#options' of your $form['select-user-group'].

For example for displaying all node types in a select list you can use the following function:

function get_node_type_info() {

  $wizard_plugins = node_type_get_types();

  $options = array();

  foreach ($wizard_plugins as $key => $wizard) {
    // Don't forget the $ before wizard
    $options[$key] = $wizard->name;

  return $options;

And then use this function to populate the '#options' like so:

$form['display_options'] = array(
  '#type' => 'select',
  '#title' => t('Component Type'),
  '#options' => get_node_type_info(),

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.