tags:

views:

97

answers:

2

I have this array that populates a dropdown menu. The key is my database key and the value is the corresponding database value. The issue I am having is that when I POST the form, I am getting the POSTed numerical value instead of the string value in the dropdown list. I could query the database to get the string but there has to be a better way of doing this as I already have both values in an array. I can't use array_search because the the array is multidimensional. Can someone please offer a hand?

Thanks

foreach($dd as $k=>$v)
{
 echo'<option value="'.$v['ace_id'].'">'.$v['arua'].'</option>';
}
A: 

The HTML input fields (this also includes select, textarea and button) only sends the name-value pairs to the server side (as been specified in the name and value attribues). They does not send any textual representation along it.

You already know the text and the labels in the server side beforehand (how else would you have printed them?), there's absolutely no point of having them in the request parameters.

You can solve this "problem" in several ways:

  1. Just specify the desired value in the option value attribute, not as option label.
  2. Add hidden input field(s) which passes the option label back.
  3. Maintain a global array in the server side memory with those key-value pairs.
  4. Go get the value from the DB.
  5. Do nothing. In most cases you actually don't need them, just write smart code.

Update: here's a basic example (without sanitity checks like isset and htmlspecialchars, but that's up to you):

$selected = $_POST['dropdownname'];

foreach ($options as $value => $label) {
    echo '<option value="' . $value . '"' . ($value == $selected ? ' selected' : '') .  '>' . $label . '</option>';
}
BalusC
Thanks for the help. I'd opt for #5 and that's what I've been trying to do. Drop downs have always been a bit of a challenge to get just right with a minimal amount of code when using the same form for inserts, updates and deletes. How would you go about doing this if it were you?
jon voight
Set the option to selected if the array key matches the request parameter value.
BalusC
Ok, that sounds super easy... Almost too easy. If you look at my array, the way it's structured, how would I test the array key? array_search wouldn't work with this type of array. Am I wrong?
jon voight
I posted an example.
BalusC
A: 

If you want the text name in the dropdown instead of the key, then put that in the value="" part. If you want both, then put both in there and seperate them with a comma and run split() on it.

TravisO
This was what I had thought of originally doing and then using explode.. or split. Yes, this would work too. I figured that maybe there was a best practice for these dropdowns. I have always struggled with getting them just right and thought that I'd ask over here.
jon voight