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

基于schemaform.io实现带条件字段的可扩展对象数组表单

我来帮你实现这个支持动态添加对象、还能根据type字段自动切换显示内容的数组表单!结合schemaform的特性,咱们用枚举字段+依赖校验+动态显隐的组合就能完美达成需求。

完整Schema配置

首先是核心的Schema定义,既要支持数组的动态添加,还要保证数据的合法性:

{
  "type": "object",
  "title": "Command Asset",
  "properties": {
    "commands": {
      "type": "array",
      "title": "Commands",
      "items": {
        "type": "object",
        "title": "Single Command",
        "properties": {
          "type": {
            "type": "string",
            "title": "Command Type",
            "enum": ["REST", "SSH"],
            "default": "REST"
          },
          "method": {
            "type": "string",
            "title": "HTTP Method",
            "enum": ["GET", "POST", "PUT", "DELETE"]
          },
          "path": {
            "type": "string",
            "title": "SSH Target Path"
          }
        },
        // 依赖校验:确保选对应类型时必填对应字段
        "dependencies": {
          "type": {
            "oneOf": [
              {
                "properties": { "type": { "enum": ["REST"] } },
                "required": ["method"]
              },
              {
                "properties": { "type": { "enum": ["SSH"] } },
                "required": ["path"]
              }
            ]
          }
        }
      }
    }
  }
}
配套Form配置(优化交互体验)

光有Schema还不够,咱们再加个Form配置,让字段能根据type自动显隐,还能自定义添加/删除按钮的文本:

[
  {
    "key": "commands",
    "add": "Add a New Command",
    "remove": "Delete This Command",
    "items": [
      {
        "key": "commands[].type",
        "type": "select",
        // 给选项加友好名称
        "titleMap": {
          "REST": "REST API Request",
          "SSH": "SSH File Operation"
        }
      },
      // 只有选REST时才显示method字段
      {
        "key": "commands[].method",
        "condition": "model.type === 'REST'"
      },
      // 只有选SSH时才显示path字段
      {
        "key": "commands[].path",
        "condition": "model.type === 'SSH'"
      }
    ]
  }
]
关键功能说明
  • 动态添加数组项:Schema里的commands数组配合Form配置的add/remove属性,用户可以随意添加或删除命令对象,完全满足“任意数量”的需求。
  • 字段自动切换:Form里的condition规则会实时监听type字段的选择,自动显示对应字段、隐藏无关字段,交互逻辑很直观。
  • 数据合法性校验:Schema的dependencies规则确保用户选了REST就必须填method,选了SSH就必须填path,避免提交无效数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:52:46