Reputation: 4610
I have an edit record page that is working but I've got a small issue with fields that are displayed as select drop down lists that reference an associated value list from a database.
I have some fields in the database with drop down lists but users can enter a value that isn't on the value list, which is expected normal behaviour. However I'm having an issue with displaying this on the web. Here's the code for one of the fields:
<select name="category">
<?php
foreach($categories as $category) {
$selected = "";
if( $category == $record->getField('category') ){
$selected = " selected";
}
$category = htmlspecialchars($category);
?>
<option value="<?php echo $category; ?>"<?php echo $selected; ?>><?php echo $category; ?></option>
<?php
}
?>
</select>
This works well when the value in the field matches one of the options from the valuelist. However when the field is empty or it doesn't match there is a problem. If the field is empty I get the first value list option appearing automatically - I can bypass that by adding a blank option which is fine.
If the value in the field doesn't match the options for the value list it doesn't appear either - I can also display the value at the top before all the value list items but if the value is the same as a value list item it will appear twice: once at the top and then in it's normal position in the list which also isn't ideal. I would like it that if the value is a member of the valuelist then it is selected in it's normal position in the list which is what the above code achieves.
Anyone tacked this scenario before and have any pointers?
Thanks, Steve
Upvotes: 0
Views: 1176
Reputation: 1637
what did you mean by "field", did you mean $record->getField('category')
? If what you want is to have that value included in your select list even if it is not an entry in the $category
array, then do this:
<select name="category">
<?php
$output = "";
$selected = false;
foreach ($categories as $category) {
$output .= "<option value=\"$category\"";
if ($category == $record->getField('category')) {
$selected = true;
$output .= " selected";
}
$output += ">$category</option>";
}
if (!$selected) {
$chosen = $record->getField("category");
$output = "<option value=\"$chosen\" selected>$chosen</option>" . $output;
}
echo $output;
?>
</select>
Upvotes: 1