> -----Original Message-----
> From: PJ [mailto:af.gour...@videotron.ca]
> Sent: 15 June 2009 23:10
> To: php-general@lists.php.net
> 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 ;
}


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to