mcpField
A
arcgis-tables-forms

arcgis-tables-forms

github.com/saschabrunnerch开发2363 次安装29 周前更新
代码仓库

关于 arcgis-tables-forms

面向使用 ArcGIS Maps SDK for JavaScript 构建要素表和属性编辑表单的开发者。介绍表格配置、选择操作、列布局、表单输入及基于表达式的行为设置。

主要功能

  1. 01配置 FeatureTable 列与显示
  2. 02内联编辑记录并管理选择
  3. 03使用多种输入类型构建表单
  4. 04分组字段并显示相关记录
  5. 05通过表达式控制可见性和验证

适用场景

  1. 01为图层创建可编辑属性表
  2. 02设计结构化的要素编辑表单
  3. 03将表格选择与地图要素同步

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/saschabrunnerch/arcgis-maps-sdk-js-ai-context --skill arcgis-tables-forms

安装后在 Claude Code 中输入/arcgis-tables-forms确认已加载。

详细介绍

ArcGIS 表格与表单

使用此技能配置 FeatureTable 组件/微件和包含各种输入元素的 FormTemplate。

导入方式

直接 ESM 导入
import FeatureTable from "@arcgis/core/widgets/FeatureTable.js";
import FeatureForm from "@arcgis/core/widgets/FeatureForm.js";
import FormTemplate from "@arcgis/core/form/FormTemplate.js";
import FieldColumnTemplate from "@arcgis/core/widgets/FeatureTable/support/FieldColumnTemplate.js";
动态导入(CDN)
const FeatureTable = await $arcgis.import(
  "@arcgis/core/widgets/FeatureTable.js",
);
const FeatureForm = await $arcgis.import("@arcgis/core/widgets/FeatureForm.js");
const FormTemplate = await $arcgis.import("@arcgis/core/form/FormTemplate.js");
const FieldColumnTemplate = await $arcgis.import(
  "@arcgis/core/widgets/FeatureTable/support/FieldColumnTemplate.js",
);

注意: 此技能中的示例使用直接 ESM 导入。使用 CDN 时,将 import X from "path" 替换为 const X = await $arcgis.import("path")。

FeatureTable 组件

基本用法
<arcgis-map item-id="YOUR_WEBMAP_ID">
  <arcgis-zoom slot="top-left"></arcgis-zoom>
</arcgis-map>

<arcgis-feature-table reference-element="arcgis-map"></arcgis-feature-table>

<script type="module">
  const map = document.querySelector("arcgis-map");
  const table = document.querySelector("arcgis-feature-table");

  const view = await map.view;
  await view.when();

  const layer = view.map.layers.find((l) => l.type === "feature");
  table.layer = layer;
</script>
主要属性
属性类型默认值描述
layerFeatureLayer要显示的图层
attribute-table-templateAttributeTableTemplate表格配置(5.0 中新增)
editing-enabledbooleanfalse启用行内编辑
filter-by-selection-enabledbooleanfalse按选中的要素筛选
highlight-disabledbooleanfalse禁用行高亮
hide-headerbooleanfalse隐藏表格标题
hide-menubooleanfalse隐藏表格菜单
hide-selection-columnbooleanfalse隐藏选择列
multiple-selection-disabledbooleanfalse禁用多行选择
multiple-sort-enabledbooleanfalse启用多列排序
page-sizenumber每页行数
auto-save-disabledbooleanfalse禁用自动保存编辑内容
definition-expressionstring筛选表达式
time-zonestring日期的时区
隐藏菜单项
属性描述
hide-menu-items-clear-selection隐藏清除选择菜单项
hide-menu-items-delete-selection隐藏删除选择菜单项
hide-menu-items-export-selection-to-csv隐藏导出为 CSV 菜单项
hide-menu-items-refresh-data隐藏刷新数据菜单项
hide-menu-items-toggle-columns隐藏切换列菜单项
hide-menu-items-zoom-to-selection隐藏缩放至选择项菜单项
主要事件
事件描述
arcgisSelectionChange行选择发生变化时触发
arcgisCellClick单元格被点击时触发
arcgisCellKeydown在单元格中进行键盘交互时触发
arcgisCellPointerover指针进入单元格时触发
arcgisCellPointerout指针离开单元格时触发
arcgisColumnReorder列顺序发生变化时触发
arcgisPropertyChange属性发生变化时触发
arcgisReady组件就绪时触发
带配置的组件
<arcgis-feature-table
  reference-element="arcgis-map"
  editing-enabled
  multiple-sort-enabled
  page-size="50"
  hide-menu-items-delete-selection
></arcgis-feature-table>

<script type="module">
  const table = document.querySelector("arcgis-feature-table");
  table.layer = featureLayer;

  table.addEventListener("arcgisSelectionChange", (event) => {
    console.log("Selection changed");
  });
</script>

FeatureTable 微件(Core API)

基本微件
import FeatureTable from "@arcgis/core/widgets/FeatureTable.js";

const featureTable = new FeatureTable({
  view: view,
  layer: featureLayer,
  container: "tableDiv",
});
已配置的微件
const featureTable = new FeatureTable({
  view: view,
  layer: featureLayer,
  container: "tableDiv",
  editingEnabled: true,
  multiSortEnabled: true,
  highlightEnabled: true,
  attachmentsEnabled: true,
  relatedRecordsEnabled: true,
  pageSize: 50,
  filterGeometry: view.extent,
});
列模板
import FieldColumnTemplate from "@arcgis/core/widgets/FeatureTable/support/FieldColumnTemplate.js";

const featureTable = new FeatureTable({
  view: view,
  layer: featureLayer,
  tableTemplate: {
    columnTemplates: [
      new FieldColumnTemplate({
        fieldName: "name",
        label: "Name",
        initialSortPriority: 0,
        direction: "asc",
      }),
      new FieldColumnTemplate({
        fieldName: "status",
        label: "Status",
      }),
      new FieldColumnTemplate({
        fieldName: "value",
        label: "Value ($)",
        textAlign: "right",
      }),
    ],
  },
});
FieldColumnTemplate 属性
属性类型描述
fieldNamestring要显示的字段
labelstring列标题文本
editableboolean是否允许编辑
visibleboolean列是否可见
frozenboolean将列固定在左侧
frozenToEndboolean将列固定在右侧
resizableboolean是否允许调整列大小
autoWidthboolean自动调整列宽
widthnumber列宽(像素)
textAlignstring文本对齐方式
textWrapboolean单元格中的文本换行
initialSortPrioritynumber排序优先级
分组列模板
import GroupColumnTemplate from "@arcgis/core/widgets/FeatureTable/support/GroupColumnTemplate.js";

const featureTable = new FeatureTable({
  view: view,
  layer: featureLayer,
  tableTemplate: {
    columnTemplates: [
      new GroupColumnTemplate({
        label: "Location",
        columnTemplates: [
          new FieldColumnTemplate({ fieldName: "city", label: "City" }),
          new FieldColumnTemplate({ fieldName: "state", label: "State" }),
          new FieldColumnTemplate({ fieldName: "country", label: "Country" }),
        ],
      }),
      new GroupColumnTemplate({
        label: "Details",
        columnTemplates: [
          new FieldColumnTemplate({ fieldName: "name", label: "Name" }),
          new FieldColumnTemplate({ fieldName: "type", label: "Type" }),
        ],
      }),
    ],
  },
});

AttributeTableTemplate(5.0 中新增)

使用 AttributeTableTemplate 配置表格显示,可在图层或要素表组件上设置。

import AttributeTableTemplate from "@arcgis/core/tables/AttributeTableTemplate.js";

const tableTemplate = new AttributeTableTemplate({
  elements: [
    {
      type: "field",
      fieldName: "name",
      label: "Name",
    },
    {
      type: "field",
      fieldName: "status",
      label: "Status",
    },
    {
      type: "group",
      label: "Location",
      elements: [
        { type: "field", fieldName: "city", label: "City" },
        { type: "field", fieldName: "state", label: "State" },
      ],
    },
  ],
  orderByFields: [{ field: "name", order: "asc" }],
});

// Set on the feature table component
const table = document.querySelector("arcgis-feature-table");
table.attributeTableTemplate = tableTemplate;

// Or set on the layer
featureLayer.attributeTableTemplate = tableTemplate;
AttributeTableTemplate 元素类型
类型类描述
fieldAttributeTableFieldElement单个字段列
groupAttributeTableGroupElement列组
relationshipAttributeTableRelationshipElement相关记录
attachmentAttributeTableAttachmentElement附件列

选择与高亮

以编程方式选择
// Select by ObjectIDs
featureTable.highlightIds.add(123);
featureTable.highlightIds.addMany([124, 125, 126]);

// Clear selection
featureTable.highlightIds.removeAll();

// Select from query
const results = await featureLayer.queryObjectIds({
  where: "status = 'active'",
});
featureTable.highlightIds.addMany(results);
监视选择变化
featureTable.highlightIds.on("change", (event) => {
  console.log("Added IDs:", event.added);
  console.log("Removed IDs:", event.removed);

  const selectedIds = featureTable.highlightIds.toArray();
  console.log("All selected:", selectedIds);
});
与地图选择同步
// Map click selects in table
view.on("click", async (event) => {
  const response = await view.hitTest(event);
  const feature = response.results.find(
    (r) => r.graphic.layer === featureLayer,
  );

  if (feature) {
    featureTable.highlightIds.removeAll();
    featureTable.highlightIds.add(feature.graphic.attributes.OBJECTID);
  }
});

// Table selection highlights on map
let highlightHandle;

featureTable.highlightIds.on("change", async () => {
  const layerView = await view.whenLayerView(featureLayer);

  if (highlightHandle) {
    highlightHandle.remove();
  }

  const objectIds = featureTable.highlightIds.toArray();
  if (objectIds.length > 0) {
    highlightHandle = layerView.highlight(objectIds);
  }
});
筛选与刷新
// Filter by geometry
featureTable.filterGeometry = view.extent;

// Filter by expression
featureTable.layer.definitionExpression = "category = 'A'";

// Refresh data
featureTable.refresh();

// Clear filters
featureTable.filterGeometry = null;
featureTable.layer.definitionExpression = null;

FormTemplate

配置要素的编辑表单。

基本 FormTemplate
import FormTemplate from "@arcgis/core/form/FormTemplate.js";

const formTemplate = new FormTemplate({
  title: "Edit Feature",
  description: "Update the feature attributes",
  elements: [
    {
      type: "field",
      fieldName: "name",
      label: "Name",
    },
    {
      type: "field",
      fieldName: "category",
      label: "Category",
    },
    {
      type: "field",
      fieldName: "description",
      label: "Description",
    },
  ],
});

featureLayer.formTemplate = formTemplate;
FormTemplate 属性
属性类型描述
titlestring表单标题
descriptionstring表单描述
elementsFormElement[]表单元素数组
expressionInfosExpressionInfo[]Arcade 表达式定义
preserveFieldValuesWhenHiddenboolean保留隐藏字段的值
表单元素类型
类型描述
fieldFieldElement - 编辑特定字段
groupGroupElement - 元素分组
textTextElement - 静态文本/HTML 内容
relationshipRelationshipElement - 相关记录
attachmentAttachmentElement - 文件附件
字段元素
{
  type: "field",
  fieldName: "name",
  label: "Name",
  description: "Enter the feature name",
  hint: "Required field",
  requiredExpression: "always-required",
  editableExpression: "$feature.status != 'locked'",
  visibilityExpression: "$feature.type != 'hidden'"
}
分组元素
{
  type: "group",
  label: "Location",
  description: "Address information",
  initialState: "collapsed",  // expanded, collapsed
  elements: [
    { type: "field", fieldName: "address", label: "Address" },
    { type: "field", fieldName: "city", label: "City" },
    { type: "field", fieldName: "state", label: "State" }
  ]
}
文本元素
{
  type: "text",
  text: "<h3>Important Instructions</h3><p>Please fill out all required fields.</p>"
}
关系元素
{
  type: "relationship",
  relationshipId: 0,
  label: "Related Inspections",
  description: "View and manage related inspection records",
  displayCount: 5,
  orderByFields: [{
    field: "inspection_date",
    order: "desc"
  }],
  editableExpression: "true"
}

输入类型

文本框输入
{
  type: "field",
  fieldName: "name",
  label: "Name",
  input: {
    type: "text-box",
    maxLength: 100,
    minLength: 1
  }
}
文本区域输入
{
  type: "field",
  fieldName: "description",
  label: "Description",
  input: {
    type: "text-area",
    maxLength: 1000,
    minLength: 0
  }
}
组合框输入
{
  type: "field",
  fieldName: "category",
  label: "Category",
  input: {
    type: "combo-box",
    showNoValueOption: true,
    noValueOptionLabel: "Select a category..."
  }
}
// Works with coded value domains - values auto-populate from domain
单选按钮输入
{
  type: "field",
  fieldName: "priority",
  label: "Priority",
  input: {
    type: "radio-buttons",
    showNoValueOption: false
  }
}
开关输入
{
  type: "field",
  fieldName: "is_active",
  label: "Active",
  input: {
    type: "switch",
    offValue: 0,
    onValue: 1
  }
}
日期选择器输入
{
  type: "field",
  fieldName: "start_date",
  label: "Start Date",
  input: {
    type: "date-picker",
    min: new Date("2020-01-01"),
    max: new Date("2030-12-31"),
    includeTime: false
  }
}
日期时间选择器输入
{
  type: "field",
  fieldName: "event_datetime",
  label: "Event Date/Time",
  input: {
    type: "datetime-picker",
    min: new Date("2020-01-01T00:00:00"),
    max: new Date("2030-12-31T23:59:59"),
    includeTime: true
  }
}
时间选择器输入
{
  type: "field",
  fieldName: "event_time",
  label: "Event Time",
  input: {
    type: "time-picker"
  }
}
条形码扫描器输入
{
  type: "field",
  fieldName: "barcode",
  label: "Barcode",
  input: {
    type: "barcode-scanner"
  }
}

基于表达式的配置

可见性表达式
const formTemplate = new FormTemplate({
  expressionInfos: [
    {
      name: "show-commercial-fields",
      expression: "$feature.property_type == 'commercial'",
    },
    {
      name: "show-residential-fields",
      expression: "$feature.property_type == 'residential'",
    },
  ],
  elements: [
    { type: "field", fieldName: "property_type", label: "Property Type" },
    {
      type: "group",
      label: "Commercial Details",
      visibilityExpression: "show-commercial-fields",
      elements: [
        { type: "field", fieldName: "business_name", label: "Business Name" },
        { type: "field", fieldName: "num_employees", label: "Employees" },
      ],
    },
    {
      type: "group",
      label: "Residential Details",
      visibilityExpression: "show-residential-fields",
      elements: [
        { type: "field", fieldName: "num_bedrooms", label: "Bedrooms" },
        { type: "field", fieldName: "num_bathrooms", label: "Bathrooms" },
      ],
    },
  ],
});
必填与可编辑表达式
// Conditionally required
{
  type: "field",
  fieldName: "inspection_notes",
  label: "Inspection Notes",
  requiredExpression: "notes-required"
}

// Conditionally editable
{
  type: "field",
  fieldName: "approved_by",
  label: "Approved By",
  editableExpression: "is-pending"
}

FeatureForm 微件

import FeatureForm from "@arcgis/core/widgets/FeatureForm.js";

const featureForm = new FeatureForm({
  container: "formDiv",
  layer: featureLayer,
  formTemplate: formTemplate,
});

// Set feature to edit
featureForm.feature = selectedGraphic;

// Listen for submit
featureForm.on("submit", () => {
  if (featureForm.feature) {
    const updated = featureForm.getValues();

    featureLayer.applyEdits({
      updateFeatures: [
        {
          attributes: {
            ...featureForm.feature.attributes,
            ...updated,
          },
          geometry: featureForm.feature.geometry,
        },
      ],
    });
  }
});

// Handle value changes
featureForm.on("value-change", (event) => {
  console.log(`${event.fieldName} changed to ${event.value}`);
});

完整示例:带地图的 FeatureTable

<!DOCTYPE html>
<html>
  <head>
    <script src="https://js.arcgis.com/5.0/"></script>
    <script
      type="module"
      src="https://js.arcgis.com/5.0/map-components/"
    ></script>
    <style>
      html,
      body {
        height: 100%;
        margin: 0;
      }
      #container {
        display: flex;
        flex-direction: column;
        height: 100%;
      }
      arcgis-map {
        flex: 1;
      }
      #tableDiv {
        height: 300px;
      }
    </style>
  </head>
  <body>
    <div id="container">
      <arcgis-map
        basemap="streets-navigation-vector"
        center="-118.805,34.027"
        zoom="11"
      >
        <arcgis-zoom slot="top-left"></arcgis-zoom>
      </arcgis-map>
      <arcgis-feature-table
        reference-element="arcgis-map"
        editing-enabled
      ></arcgis-feature-table>
    </div>

    <script type="module">
      const FeatureLayer = await $arcgis.import(
        "@arcgis/core/layers/FeatureLayer.js",
      );

      const mapElement = document.querySelector("arcgis-map");
      const view = await mapElement.view;
      await view.when();

      const featureLayer = new FeatureLayer({
        url: "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/Trailheads/FeatureServer/0",
      });
      mapElement.map.add(featureLayer);

      const table = document.querySelector("arcgis-feature-table");
      table.layer = featureLayer;

      // Highlight table selection on map
      let highlightHandle;

      table.addEventListener("arcgisSelectionChange", async () => {
        const layerView = await view.whenLayerView(featureLayer);

        if (highlightHandle) {
          highlightHandle.remove();
        }

        const objectIds = table.highlightIds?.toArray();
        if (objectIds && objectIds.length > 0) {
          highlightHandle = layerView.highlight(objectIds);
        }
      });
    </script>
  </body>
</html>

完整示例:带编辑器的 FormTemplate

<!DOCTYPE html>
<html>
  <head>
    <script src="https://js.arcgis.com/5.0/"></script>
    <script
      type="module"
      src="https://js.arcgis.com/5.0/map-components/"
    ></script>
    <style>
      html,
      body {
        height: 100%;
        margin: 0;
      }
    </style>
  </head>
  <body>
    <arcgis-map
      basemap="streets-navigation-vector"
      center="-118.805,34.027"
      zoom="13"
    >
      <arcgis-zoom slot="top-left"></arcgis-zoom>
      <arcgis-editor slot="top-right"></arcgis-editor>
    </arcgis-map>

    <script type="module">
      const FeatureLayer = await $arcgis.import(
        "@arcgis/core/layers/FeatureLayer.js",
      );

      const mapElement = document.querySelector("arcgis-map");
      const view = await mapElement.view;
      await view.when();

      const layer = new FeatureLayer({
        url: "https://services.arcgis.com/.../FeatureServer/0",
      });
      mapElement.map.add(layer);

      const editor = document.querySelector("arcgis-editor");
      editor.layerInfos = [
        {
          layer: layer,
          formTemplate: {
            title: "Property Information",
            description: "Enter property details",
            preserveFieldValuesWhenHidden: true,
            expressionInfos: [
              {
                name: "is-commercial",
                expression: "$feature.type == 'commercial'",
              },
            ],
            elements: [
              {
                type: "field",
                fieldName: "name",
                label: "Property Name",
                input: { type: "text-box", maxLength: 100 },
              },
              {
                type: "field",
                fieldName: "type",
                label: "Property Type",
                input: { type: "combo-box" },
              },
              {
                type: "group",
                label: "Commercial Details",
                visibilityExpression: "is-commercial",
                elements: [
                  {
                    type: "field",
                    fieldName: "business_type",
                    label: "Business Type",
                  },
                  { type: "field", fieldName: "sqft", label: "Square Footage" },
                ],
              },
              {
                type: "field",
                fieldName: "inspection_date",
                label: "Last Inspection",
                input: { type: "date-picker" },
              },
              {
                type: "field",
                fieldName: "notes",
                label: "Notes",
                input: { type: "text-area", maxLength: 500 },
              },
            ],
          },
        },
      ];
    </script>
  </body>
</html>

参考示例

  • feature-table - FeatureTable 组件用法
  • widgets-featuretable-editing - 使用 FeatureTable 进行编辑
  • widgets-featuretable-map - 将 FeatureTable 与地图集成
  • widgets-featuretable-relates - 在 FeatureTable 中显示相关记录
  • editing-groupedfeatureform - 分组要素表单布局
  • editing-featureform-fieldvisibility - 控制表单中的字段可见性

常见问题

  1. 字段名称必须匹配:fieldName 必须与图层字段名称完全一致(区分大小写)。

    // Layer has field "PropertyName"
    {
      fieldName: "PropertyName";
    } // Correct
    {
      fieldName: "propertyname";
    } // Wrong - case sensitive
    
  2. 编码值域:ComboBox 会自动填充值域中的值。

    // If field has coded value domain, values come from domain
    { type: "field", fieldName: "status", input: { type: "combo-box" } }
    // Dropdown shows domain values automatically - no manual options needed
    
  3. 表达式名称:通过名称字符串引用表达式,而不是表达式文本。

    expressionInfos: [{ name: "my-expr", expression: "..." }],
    elements: [{
      visibilityExpression: "my-expr"  // String reference to name
    }]
    
  4. 图层必须可编辑:启用编辑前,请检查图层功能。

    await layer.load();
    if (layer.capabilities?.editing?.supportsUpdateByOthers) {
      featureTable.editingEnabled = true;
    }
    
  5. 容器大小:FeatureTable 微件需要为其容器显式指定高度。

    #tableDiv {
      height: 400px; /* Required - table won't render without explicit height */
      width: 100%;
    }
    
  6. 高亮 ID 类型:highlightIds 需要 ObjectID 数字,而不是字符串。

    featureTable.highlightIds.add(123); // Correct - number
    featureTable.highlightIds.add("123"); // Wrong - string
    

相关技能

  • 有关 Editor 配置、applyEdits 和版本控制,请参阅 arcgis-editing。
  • 有关 PopupTemplate 配置,请参阅 arcgis-popup-templates。
  • 有关命中测试和地图选择,请参阅 arcgis-interaction。
  • 有关 FeatureLayer 配置,请参阅 arcgis-layers。

评论

支持 Markdown