Page 1 of 1

Forms in PHP select - multiple

Posted: Fri Feb 07, 2003 3:57 pm
by dstefani
Hello,

I'm generating a <select multiple size=5> list.
After the form is submitted, I regenerate the list, but this time, the values the user selected in his multiple select are preloaded, saving the state of his last form submission.

I've got it all working, except for the fact that when reloading the select list, it skips the first "selected" and then writes the rest.
For instance, if you selected one from the list, it wouldn't reload any as selected. If you had selected two, it would mark as selected the second on you choose and so on. I must be looking right at the problem and don't see it.

Here is the code,

Thanks,

Don

Code: Select all

<?

// each select is first an array
$arr_pizza = array
(
'All' => '%',
'Cheese' => 'cheese',
'Combo' => 'combo',
'Veggie' => 'veggie'
);

?>
<hr>
<b>Hold down control while clicking selections</b><p>
<form action="<?php echo $HTTP_SERVER_VARS&#1111;'PHP_SELF']; ?>" method="post">
Pizza types: <p>

<select multiple name="pizza&#1111;]" size=5>
<?
foreach ($arr_pizza as $key => $value) 
&#123;
    if(!isset($_POST&#1111;'set'])) // onLoad
    &#123;
        echo "<option value="$value">$key _out</option>\n";
    &#125;
    else // onSubmit
    &#123;
        if(array_search($value,$_POST&#1111;'pizza']))
        &#123;
            echo "<option value="$value" selected>$key</option>\n";
        &#125;
        else
        &#123;
            echo "<option value="$value">$key _loop</option>\n";
        &#125;
    &#125;
&#125;
?>
   <option>----------------------------------------</option>
   </select><br>
   <input type="hidden" name="set" value="1">
   <input type="submit" name="submit" value="submit">
</form>

Posted: Fri Feb 07, 2003 4:54 pm
by superwormy
I assume you're doing something like this:

<?php

print ("option value=\"\" ");

if (array_search($array, "currentoption")) {
&nbsp;&nbsp;&nbsp;print (" SELECTED ");
}

print ($value . "</option>");

?>


Right? The reason is that the key for the first selected value is 0, so PHP interprets that as FALSE, and doesn't select the value. Try adding this before you build your multiple select box:

array_unshift ($array, "stupiduslessvaluethatwillneverappear);

Now build your select box and it'll work correctly. DId that makes sense?

Posted: Fri Feb 07, 2003 5:03 pm
by dstefani
I had just got to the point were I figured out it was the 0 in the multi select array. Thanks for the jump to unshift!

So cool! Works like a charm.

Don