Forums

Make an option of a dynamic dropdown selected

alinden 09 Dec, 2014
Hi,

I have a form that queries a record from the database to fill the values. I do that by using a token in the url. Also I use dynamic dropdowns / selectboxes, that are filled with data from an other table.

Is it possible to set an option of that select box to selected? So according to the value in the database record?

Thanks, Aron.
alinden 10 Dec, 2014
Answer
I already succeeded. I found the solution on:
http://greyhead.net/chronoforms/using-php-to-create-select-dropdowns

here the code I used (in a custom element):

<?php
$options = array();
$options[] = "<option value=''>--?--</option>";
$db =& JFactory::getDBO();
$query = "
  SELECT `id`, `naam`
    FROM `0rnbi_instroom`
      ORDER BY `naam`;
";
$db->setQuery($query);
$data = $db->loadObjectList();
foreach ( $data as $d ) {
  $selected = '';
 if ( isset($form->data['locatieId']) && $form->data['locatieId'] == $d->id ) {
    $selected = "selected='selected'"; 
  }
  $options[] = "<option value='{$d->id}' $selected >{$d->naam}</option>";
}
?>
<select class="" id="locatieId" size="1" name="locatieId">
<?php echo implode("\n", $options); ?>
</select>
This topic is locked and no more replies can be posted.