Make an option of a dynamic dropdown selected

Set a dynamic dropdown option as selected based on database values.

Overview

The issue occurs when a form loads data from a database record but the associated dynamic dropdown does not automatically select the matching option.
Use a custom element to query the dropdown data and compare each value to the stored form data, adding a 'selected' attribute to the matching option.

Answered
al 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.
al 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.