views:

75

answers:

2

I have a picture uplaod tool which reloads the page (which contains a form) whenever a picture is chosen.

I have this code to "remember" the drop list options selected, so basically I am creating options using php:

$posted_type=$row['9_type']; //From mysql db

$types = array('Clothes', 'Bags', 'Others');
$category_table .= "<select name='type' id='type'>";

foreach ($types as $type) 
{
$category_table .= "<option id='" . $type . "' value='" . $type . "' " . 
(($_POST['type'] == $type || $posted_type==$type)?'selected':'') . ">" . $type . "</option>\n";
}

This code has a problem, if the page is reloaded, and the "type" drop-list is changed, then there will be two "SELECTED" attributes added instead of one.

I need to have something like:

isset($_POST['type']) THEN add "SELECTED" and ignore the $posted_type variable comparison

Is there any short code for this?

I am pretty new to PHP, and it will take me a day just to change all categories and add a "if-case" just to check if the $_POST has been set already...

Anybody know of a good idea?

Thanks

A: 

Just set a different variable outside the actual HTML-building:

$selectedType = $posted_type;
if (isset($_POST['type']))
{
    $selectedType = $_POST['type'];
}

foreach ($types as $type)
{
    $category_table .= "<option id='" . $type . "' value='" . $type . "' " . (($selectedtype == $type) ? 'selected' : '') . ">" . $type . "</option>\n";
}
Andrew
+1  A: 

Check the selected type before you enter the foreach loop:

$selected = $posted_type;
if (isset($_POST['type'])) {
    $selected = $_POST['type'];
}    

foreach ($types as $type) {
    $html .= '<option '
          .= 'id="' . $type . '" '
          .= 'value="' . $type . '" ';

    if ($selected == $type) {
        $html .= "selected";
    }

    $html .= '>'
          .= $type
          .= '</option>';
}
Jurian Sluiman