表单 – 验证CodeIgniter中的表单下拉列表

我使用CodeIgniter的表单帮助器和表单验证库来构建我的表单.我无法使下拉菜单“粘稠”,也找到适当的验证规则.

这是我如何填充下垂:

foreach($events as $event){
$options[$event->event_title] = $event->event_title;
}
$firstItem = '<option>Please select one...</option>';
echo form_dropdown('events',$options,'',$firstItem);

这是从存储在数据库中的事件构建选项.表单看起来很好,并正确填充所有字段.

不过,当我提交表单时,下拉菜单不会保留所选的值?此外,我应该如何验证它,我想让它需要,但我也想确保我除了下拉菜单中的第一个选项“请选择一个…”

提前致谢.

干杯,
GAZ

解决方法

你在看这个吗?我会告诉你我已经处理了,但这一切都发生在控制器中:
// 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 => $值
我的案件中的关键字是国家编号,值是国家名称.我有对’0’=>在我的国家/地区数组的开始,“NONE”,所以用户不能选择一个.如果我想要这样做需要你的情况,我可以把它设置为’-1’=> “请选择…”,它不会验证,因为-1不是自然数.

希望我的漫游有帮助!

编辑:

好的,所以在使用form_dropdown()创建下拉菜单之前,您要做的是检查来自POST数组的选定值.

在CI的情况下,您可以使用函数set_value($input),所以在我的示例窗体中,我可能会执行以下操作:

$selected = (!empty(set_value('country'))) ? set_value($country) : '';

form_dropdown('country',$selected)

所以现在,下拉列表的选定值将被设置为在最后一个帖子中选择的值.您可能需要检查该值以确保其有效.如果没有选择任何内容,那么您可以将$select设置为数据库中当前的值,或者您选择的认值.

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些