Reputation: 69
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
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
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
Reputation: 116160
Just a few possible issues:
You never reset the variable $selected
. That means that every item, starting with the right one, will have the attribute 'selected' set.
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.
If there are 'holes' in your sort ordering, $x
may never match the sort order.
$item_data
is never set in your loop.
Upvotes: 0