Are you doing this in a view? I'll show you have I handle this, but it all happens in a controller:
// first, we can set a validation rule for the input 'country' (our dropdown), in this case it is required, and must be a natural number. You can look up more rules in the CI user guide, and you can write your own functions as well and add them to the 3rd parameter here. I believe some native PHP functions can be used as well.
$this->form_validation->set_rules('country', 'Country', 'required|is_natural');
// the form is not valid! we'll enter this block whenever the form validation rules above are not met, as well as when first going to this controller-action.
if ($this->form_validation->run() == FALSE) {
// buid your form, there's some CI functions to help with this that I'm using
$my_form = form_open('user/edit', 'class="superform"')
. form_fieldset()
. '<ol>'
. '<li>'
. form_label('Country<br/>', 'country')
// so here is the dropdown, matching the name given to the validation rule we've set, the second parameter takes an array, which I am grabbing from a model, the last parameter is the 'selected; value, which I am grabbing from some variable, if it's not present the first item in the dropdown will obviously be selected
. form_dropdown('country', $this->Country_model->get_countries_dropdown(), $user->country)
. form_error('country', ' <em>', '</em>'
. form_submit('mysubmit', 'Save', 'class="button"')
. '</li>'
. '</ol>'
. form_fieldset_close()
. form_close()
);
// sending the form variable to my view, where i will simply <?=$my_form?> it
$this->load->view('user_edit', $my_form);
} else {
// form has validated! do something!
}
The form_dropdown() function takes an array that is setup like:
$key => $value
Where the key in my case is a country id, and the value is the countries name. I have the pair '0' => 'NONE' at the start of my country array, so the user cannot choose one. If i wanted to make this required like your situation, I could set it to '-1' => 'Please select...' and it would not validate, as -1 is not a natural number.
Hope my rambling helps!
Edit:
Okay, so before you create the dropdown with form_dropdown(), what you'll want to do is check for a selected value from coming from the POST array.
In the case of CI, you can use the function set_value($input), so in my example form I might do something like:
$selected = (!empty(set_value('country'))) ? set_value($country) : '';
form_dropdown('country', $this->Country_model->get_countries_dropdown(), $selected)
So now the selected value of the dropdown will be set to what was selected on the last post. You might want to check that value to make sure it's valid. If nothing was selected, then you could set $selected as something like the value currently in the database, or a default value you've chosen.