您是在视图中执行此操作吗?我会告诉你我已经处理了这个,但这一切都发生在控制器中:
// 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!
}
form_dropdown() 函数采用如下设置的数组:
$key => $value
在我的例子中,键是国家 ID,值是国家名称。我在国家/地区数组的开头有一对 '0' => 'NONE',所以用户不能选择一个。如果我想像您的情况一样要求这样做,我可以将其设置为 '-1' => 'Please select...' 并且它不会验证,因为 -1 不是自然数。
希望我的漫谈有所帮助!
编辑:
好的,所以在使用 form_dropdown() 创建下拉列表之前,您要做的是检查来自 POST 数组的选定值。
在 CI 的情况下,您可以使用函数 set_value($input),所以在我的示例表单中,我可能会执行以下操作:
$selected = (!empty(set_value('country'))) ? set_value($country) : '';
form_dropdown('country', $this->Country_model->get_countries_dropdown(), $selected)
所以现在下拉列表的选定值将设置为上一篇文章中选择的值。您可能需要检查该值以确保其有效。如果没有选择任何内容,那么您可以将 $selected 设置为数据库中当前的值,或者您选择的默认值。