user1724167
user1724167

Reputation: 69

Add Edit Form with select element

I have one form that is used for adding and editing. My goal here is to on the add form have it pre-select the count(items)+1 value. On the edit form I need it to pre-select the value from the database when it it matches the increment of the for loop. Right now the $selected value isn't working and I"m not sure how to implement the part for the add form. Any ideas?

<?php for($x = 1; $x <= count($items)+1; $x++)
{
    if (isset($item_data))
    {
        $selected = $item_data->item_sort_order === $x ? ' selected="selected"' : '';
    }
    echo '<option value="'.$x.'"';
    if (isset($selected)) { echo $selected; }
    echo '>'.$x.'</option>';
}
?>

Upvotes: 1

Views: 137

Answers (3)

topherg
topherg

Reputation: 4303

I think you need to reset the $selected variable each time. Once its set, then it remains so. Try this:

for($x = 1; $x <= count($items) + 1; $x++) {
    echo '<option value="' . $x . '"';
   if ((isset($item_data) && $item_data->item_sort_order === $x)
       echo ' selected="selected";
   echo '>' . $x . '</option>';
}

EDIT:

for($x = 1; $x <= count($items) + 1; $x++) {
    echo '<option value="' . $x . '"';
   if ((isset($item_data) && (int)$item_data->item_sort_order == $x)
       echo ' selected="selected";
   echo '>' . $x . '</option>';
}

Upvotes: 1

iMoses
iMoses

Reputation: 4348

Does it change anything?

for($x = 1, $length = count($items) + 1; $x <= $length; $x++) {
    echo '<option value="' . $x . '"' .
        (isset($item_data) && ($item_data->item_sort_order === $x) ? ' selected="selected"' : '') .
        '>' . $x . '</option>';
}

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116160

Just a few possible issues:

  1. You never reset the variable $selected. That means that every item, starting with the right one, will have the attribute 'selected' set.

  2. You use the strict === operator, which I approve of, but if $item_data->item_sort_order doesn't contain an int value, this comparison won't match. You can use var_dump to check the value and type of that property.

  3. If there are 'holes' in your sort ordering, $x may never match the sort order.

  4. $item_data is never set in your loop.

Upvotes: 0

Related Questions