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

使用dbc动态生成多Tab表单,提交时如何获取对应表单的Select值?

仅获取当前提交表单内Select值的解决方案

核心思路

给每个下拉选择框(Select)的ID添加所属表单的索引标识,在表单提交时通过触发事件定位到目标表单的索引,再过滤出对应索引下的所有Select数据。

步骤1:调整组件ID结构

修改表单和Select的ID定义,让每个Select明确关联到所属的表单:

表单ID保持原有结构

dbc.Form(
    id={"type": "form", "index": form_idx},  # form_idx为当前表单的唯一索引(如标签页序号)
    children=list_of_selects
)

给Select添加表单索引关联

dbc.Select(
    key=key,
    id={
        "type": "select",
        "form_index": form_idx,  # 与所属表单的index一致,建立关联
        "key": key  # Select自身的唯一标识
    },
    options=options,
    size="sm"
)

步骤2:编写回调逻辑

通过监听所有表单的提交事件,结合Select的关联索引过滤目标数据:

@callback(
    Output(toaster, "is_open"),
    Input({"type": "form", "index": ALL}, "n_submit"),
    State({"type": "select", "form_index": ALL, "key": ALL}, "id"),
    State({"type": "select", "form_index": ALL, "key": ALL}, "value"),
    prevent_initial_call=True
)
def handle_form_submit(form_submits, select_ids, select_values):
    # 定位触发提交的表单索引
    # 遍历找到非空且大于0的n_submit对应的索引(表单index从1开始的话,触发索引+1即为目标form_index)
    triggered_form_index = [idx + 1 for idx, n in enumerate(form_submits) if n and n > 0][0]
    
    # 过滤当前表单的Select数据
    current_form_data = {}
    for select_id, val in zip(select_ids, select_values):
        if select_id["form_index"] == triggered_form_index:
            current_form_data[select_id["key"]] = val
    
    # 此处添加你的业务处理逻辑(比如校验、提交数据等)
    print("当前提交表单的Select数据:", current_form_data)
    
    return True  # 控制提示框显示

关键说明

  1. 动态组件兼容:无论表单是预定义还是用户新增标签页时动态生成的,Dash的模式匹配ID都能正常捕获组件事件和状态
  2. 索引一致性:确保Select的form_index与所属表单的index严格对应,这是过滤数据的核心依据
  3. 触发事件定位:通过遍历form_submits数组找到触发提交的表单索引,避免获取无关表单的Select数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 19:55:01