0

Maybe there is a better way to do this. What I'm trying to do is generate on the the fly a Select box for a form based off of a SQL query.

Right now the code below works, however a few oddities. The default value specified below does not show up. I'm wondering does this have to be a valid result returned? Also my drop down shows the SQL results, however the foreach loop seems to go an extra iteration which causes a stray value of 2 to return to the list. Is there a way to stop that. And of course if I'm going about the structuring of this all wrong please let me know.

Thanks

$sqlplatform = "SELECT vid, name FROM {taxonomy_vocabulary} WHERE vid >= 4";
$i = 0;
$result = db_query($sqlplatform);
foreach ($result as $row){
  $option[] = $row->name;
  $i++;
}
$form['multiple_dev']['platform'] = array(
'#type' => 'select',
'#title' => t('Select a Platform'),
'#options' => array(
  $i => t($option),
),
'#default_value' => 'Platform Type',
);

1 Answer 1

1

Each item in your options array needs to be keyed by something; the default value will then come from that. At the moment you're not adding the options array to the element in quite the right way which is probably why you're seeing some strange results.

Your code should probably look more like this:

$result = db_query($sqlplatform);
$options = array();
foreach ($result as $row) {
  $options[$row->vid] = t($row->name);
}

$form['multiple_dev']['platform'] = array(
  '#type' => 'select',
  '#title' => t('Select a Platform'),
  '#options' => array(0 => t('Platform Type')) + $options,
  '#default_value' => 0
);

I've made the assumption that you're trying to get an option into the top of the select list entitled 'Select a Platform', and that you want that item to be selected by default.

I think that might be where the confusion is; the default value should be the key of the option you want selected when the select list is first displayed, it's not used to add an extra option to the list.

1
  • Thank was exactly what I was looking for. Thank you also for the quick concise explanation when using the default_value option.
    – rsaturns
    Commented Jun 12, 2012 at 23:05

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.