You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter框架multiselect多选框数据增删及初始选中适配问题

multiselect多选组件逻辑修复方案

问题根因说明

  • 初始全选中:视图层option的选中判断逻辑错误,无论是否匹配都输出selected属性
  • 提交更新失效:① 控制器调用模型时漏传房源ID参数 ② 模型的update_batch逻辑不适用于多对多关联表的变更场景,既不能删除取消选中的记录,也无法新增未关联的新选项

1. 视图层代码修改

<select name="curations[]" id="curations" multiple class="form-control multiselects" <?php echo (isset($read) ? $read:''); ?>>
<?php 
$checked = array();
foreach($get_curation as $key => $value){ 
    $checked[] = $value['curations_id'];
}
if($curations){ 
    foreach($curations as $cur){ 
?>
<option value="<?php echo $cur['id']; ?>" <?php echo in_array($cur['id'], $checked) ? 'selected' : ''; ?>><?php echo $cur['title']; ?></option>
<?php 
    }
} 
?>
</select>

修改点:

  • 去掉select标签重复的multiple属性
  • 修正option选中判断逻辑,只有匹配到已关联ID时才输出selected

2. 控制器层代码修改

// 接收提交的选中项,没选中时默认为空数组
$curationsPost = $this->input->post('curations') ?? [];
$curationsArray = array();
foreach($curationsPost as $cp){
    if ($cp != ''){
        $curationsArray[] = [
            'listings_id' => $id,
            'curations_id' => $cp
        ];
    }
}
// 调用模型时传入房源ID参数
$this->listings_model->update_curations($curationsArray, $id);

修改点:

  • 兼容全不选的场景,即使没有选中项也调用模型清空关联
  • 调用模型时补传$id参数,匹配模型的入参要求

3. 模型层代码修改

function update_curations($curationsArray, $id)
{
    // 先删除当前房源所有旧的关联记录
    $this->db->where('listings_id', $id);
    $this->db->delete('crm_property_curation');
    
    // 有新选中项时批量插入
    if(count($curationsArray) > 0){
        $this->db->insert_batch('crm_property_curation', $curationsArray);
    }
    return true;
}

修改点:

  • 采用「先清空旧关联,再插入新关联」的逻辑,天然兼容删除取消项、新增新选项的需求,不需要复杂的差异对比
  • 移除无效的update_batch逻辑,适配仅存储两个关联ID的表结构

内容的提问来源于stack exchange,提问作者H2O

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 16:45:01