1

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->prepare("SELECT admin_name, adminuser_id FROM adminuser_tbl");
if ($stmt->execute()) {
$stmt->setFetchMode(PDO::FETCH_OBJ);
$user_list = array();
foreach ($stmt as $row) {
    $user_list[$row->adminuser_id] = $row->admin_name;
}
}


$form['user_list']=array(
    '#type'=>'select',
    '#title' => t('Users'),
    '#options' => $user_list,
    '#multiple' => false,
    '#attributes'=>array('size'=>4),
    '#weight'=>8,
);
0
3

In a while looping over your result, populate array.

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

Or, as Clive suggested:

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

Then simply use this array

'#options' => $user_list,

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

while ( ($row = $stmt->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 =".

7
  • 1
    Or even quicker: $user_list = $stmt->fetchAll(PDO::FETCH_KEY_PAIR); (would mean the query parameters need to be reversed to user_id, name) – Clive Aug 1 '13 at 11:12
  • @Clive I usually make some operations in the loop, too. And Drupal's DB api don't have PDO::FETCH_KEY_PAIR as far as I remember... So I just forgot, my mistake. – Mołot Aug 1 '13 at 11:17
  • We have fetchAllKeyed() which is functionality equivalent :) – Clive Aug 1 '13 at 11:20
  • @Clive Good to know. I'm yet to encounter a situation where I will not need a loop anyway ;) If I will, I hope I'll remember this. – Mołot Aug 1 '13 at 11:21
  • @Clive I have edited the question, with what I have tried, I'm getting a blank box? I'm obviously doing something wrong? the array $user_list is empty – Tom Aug 1 '13 at 11:27

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.