RE: [PHP] populate form input option dropdown box from existing data

[email protected] ("Dajve Green")
Newsgroups php.general
Message-ID <[email protected]>
> -----Original Message-----
> From: PJ [mailto:[email protected]]
> Sent: 15 June 2009 23:10
> To: [email protected]
> Subject: [PHP] populate form input option dropdown box from existing data
> 
> I am having difficulties figuring out how enter retrieved data into a
> dropdown box for editing. Here's a snippet:
> ...snip
> <select name="categoriesIN[]" multiple size="8">
>         <option value="1">Civilization</option>
>         <option value="2">Monuments, Temples &amp; Tombs</option>
>         <option value="3">Pharaohs and Queens</option>... snip
> 
> As I understand it, I need to put an array ( $categoriesIN[] ) somewhere
> in the above code... or do I need to insert a series of value "selected"
> fields for the values?
> The closest thing to what I need, seems to be in this post:
> http://www.hpfreaks.com/forums/index.php?topic=165215
> But it doesn't appear too inviting... not sure if they ever got it to
> work...
> 

Hi,

Something like this should work for you

<?php
  // Set up initial values
  // This could be hard-coded or brought in from DB or other source
  $categoriesIN_options = array(1 => 'Civilzation',
					  2 => 'Monuments, Temples &amp;
Tombs',
					  3 => 'Pharaohs and Queens',
					  );
  // Create a holder for values posted if you want 
  // to repopulate the form on submission
  $selected_clean	= array();
  // Check for passed values and validate
  if (array_key_exists('categoriesIN',$_REQUEST)) {
    // Prevents errors with the foreach 
    $passed_categoriesIN = (array)$_POST['categoriesIN'];
    foreach ($passed_categoriesIN as $options_key) {
      // If the value isn't in our pre-defined array, handle the error
      if (!array_key_exists($options_key,$categoriesIN_options)) {
        // Handle error
        continue;
      } 
      $selected_clean[] = $options_key;
    }
  }
?>
[snip]
<select name='categoriesIN' multiple size='8'>
  <?php // Loop over the options set above
    foreach ($categoriesIN_options as $key => $value) {
      echo "<option value='{$key}'";
      // Repopulate with selected
      if (in_array($key,$selected_clean)) {
        echo " selected='selected'";
      }
      echo ">{$value}</option>\n";
    }
  ?>
</select>


--

for (thoughts, ramblings && doodles) {
  goto http://dajve.co.uk ;
}
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.