Hi using Drupal 5.

I have a form I'm creating with Drupal API.

I want to create a SELECT drop down menu with a list of states.

Sure I could hard code it like this...

    '#options' => array(
      'Arizona' => t('Arizona'),
      'Arkansas' => t('Arkansas'),
      'Utah' => t('Utah'),
      ...
    ),

But wouldn't it be nice to populate an array of States from my database (it is dynamic data, states come and go in my application and are used intermmittently)?

How would I do this?

I've tried:

  db_set_active('mydb');
  $query = "SELECT `State` FROM `mytable`";
  $result = mysql_query($query);
  $states = mysql_fetch_array($result, MYSQL_ASSOC);
  db_set_active('default'); 

$state['chosen_state'] = array(
    '#type' => 'select', 
    '#title' => t('Select a state or region report'),
    '#options' => $states
  );

But that doesn't work...how can I make this Array() work? Can't find any examples on the Drupal site.

Comments

nevets’s picture

mysql_fetch_array() only returns a single record in array format, what you need to do is loop through the data and build up $states, something like this.

  db_set_active('mydb');
  $query = "SELECT `State` FROM `mytable`";
  $result = mysql_query($query);
  $states = array();
  while ( $state = mysql_fetch_object($result) ) {
    $states[$state->State] = $state->State;
  }
  db_set_active('default'); 
JimmyReload’s picture

Awesome!

This is exactly what I've been looking for and it works a treat :)

stoob’s picture

Nevets rocks! Hey thanks for the quick help. It worked perfectly.

Anonymous’s picture

Hi old thread,

now, what if

1) I was using D6 and

2) The options were not coming from a db query, but from a predefined array like:

$options = array ('op1', 'op2', 'op3', 'op4');

Simply using #options => $options does create a select box, but no options. How do I prepare the array for the form API?

Anonymous’s picture

It seems, it was a focus problem. The array was not available within the function. Now it works.