如何清除Tom Select历史选中选项?Symfony UX配置问题
问题:Symfony UX Autocomplete + Tom Select 子分类重置后旧选项残留
场景说明
- 基于Symfony UX Autocomplete和Stimulus配置了两个Tom Select选择框:
- 主分类(示例值:
Batterie démarrage moto) - 多选子分类,选项为当前选中主分类下的子项(示例值:
Batterie moto AGM、Batterie moto GEL)
- 主分类(示例值:
- 两个选择框均通过AJAX加载外部数据
- 主分类控制器的change事件处理逻辑:
_onConnect(event) { this.#tomSelect = event.detail.tomSelect; this.#tomSelect.on('change', this._onChange.bind(this)); } _onChange(value) { this.dispatch("change", { detail: { id: value } }); if (value) { this.#tomSelect.blur(); } }
- 子分类通过
data-action="erp--product--main-category:change@window->erp--product--sub-categories#reset"绑定reset动作,预期实现:- 重置子分类的所有选项(包括已选和未选状态)
- 更新子分类Tom Select的自动补全URL,带上新的主分类ID
遇到的问题
执行reset动作后,子分类Tom Select加载并显示了新的选项,但之前选中的子分类仍会出现在下拉列表中,且这些旧选项还保留在原生<select>元素内部。
已尝试的解决方法
- 调用Tom Select的多个内置清除方法:
// this.#tomSelect 为Tom Select实例 this.#tomSelect.clear(); this.#tomSelect.clearOptions(); this.#tomSelect.clearCache(); this.#tomSelect.refreshOptions(); this.#tomSelect.sync();
- 在Symfony中配置Tom Select选项:
"tom_select_options" => [ "create" => false, "persist" => false, ]
当前可行的解决方案
在调用Tom Select的清除方法后,直接重置原生<select>元素的HTML内容:
this.#tomSelect.clear(); this.#tomSelect.clearOptions(); this.element.innerHTML = '';
疑问
该方案是否为最优解?有没有其他更符合规范的解决办法?
内容的提问来源于stack exchange,提问作者Thomas
相关产品推荐
相关产品推荐

