How to populate a dropdown list from array in FORM API Hopefully this is clearer, and my last question in a long time!

Using PDO I have connected to an external DB, I can query this and return an array of values, Using html/php I can populate a standard select box. However I am unsure how to do this in the Form API, taking the array from the second paragraph, or do I query within the form item that produces the drop down? I want to take the name and the id, display the name. So that I can store the ID later.

      $stmt = $conn-&gt;prepare("SELECT admin_name, adminuser_id FROM adminuser_tbl");
if ($stmt-&gt;execute()) {
$stmt-&gt;setFetchMode(PDO::FETCH_OBJ);
$user_list = array();
foreach ($stmt as $row) {
    $user_list[$row-&gt;adminuser_id] = $row-&gt;admin_name;
}
}


$form['user_list']=array(
    '#type'=&gt;'select',
    '#title' =&gt; t('Users'),
    '#options' =&gt; $user_list,
    '#multiple' =&gt; false,
    '#attributes'=&gt;array('size'=&gt;4),
    '#weight'=&gt;8,
);
In a while looping over your result, populate array.

$user_list = array();
while ($row = $stmt-&gt;fetch()) { // See this line in your original code
   $user_list[$row-&gt;user_id] = $row-&gt;name; 
   // Apply transformations and conditions here, if needed
}


Or, as Clive suggested:

$user_list = $stmt-&gt;fetchAll(PDO::FETCH_KEY_PAIR);


Then simply use this array

'#options' =&gt; $user_list,




By the way, if you really want to make assignment in condition, proper way to write it is:

while ( ($row = $stmt-&gt;fetch()) )


As you can see, assignment is wrapped in double parentheses. It is the way to say future developers and code review tools "yes, it is not a typo, I really wanted it this way, I did not forgot about second =".