I want the DropDown text to be retained when the Form returns from POST. How to maintain the state?
You have to set the selected
attribute on the option
element.
See http://reference.sitepoint.com/html/option/selected
<form>
<label for="favoritefood">Favorite food</label>
<select name="favoritefood" id="favoritefood">
<option value="che">Cheese</option>
<option value="egg" selected="selected">Egg</option>
<option value="cab">Cabbage</option>
</select>
</form>
The $_POST
array will either contain the numeric index of the option element or the value
if this attribute is specified. In the example above, $_POST['favoritefood']
contains 'egg'. You could build a helper that builds the option elements for you, e.g.
<?php
class HtmlHelper
{
public static function option($value, $label, $selected)
{
$selected = ($value === $selected) ? ' selected="selected"' : '';
return sprintf('<option value="%s"%s>%s</option>%s',
$value, $selected, $label, PHP_EOL);
}
}
// Usage to get the above Selectbox options
echo HtmlHelper::option('che', 'Cheese', $_POST['favoritefood']),
HtmlHelper::option('egg', 'Egg', $_POST['favoritefood']),
HtmlHelper::option('cab', 'Cabbage', $_POST['favoritefood']);
Of course, it would be smarter to have a Selectbox helper instead which you can pass the options and the POST array in one go, instead of calling it for each option separately. I leave it up to you to build this.
If you are not building your Select options dynamically with PHP, you can select the option by adding a small javascript to your page that you pass the value set for favoritefood from the $_POST array and have the script select the option. See the answers to this question for possible code.