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

Xrm.WebApi获取查找字段ID和名称时代码执行异常问题咨询

问题原因及修复方案

核心错误点

  • 结果集读取路径错误:Xrm.WebApi.retrieveMultipleRecords 成功回调返回的results对象中,实体数据存放在results.entities数组内,直接遍历results对象会读取到分页链接等非业务数据,无法获取实体字段值。
  • 字段取值方式错误:WebApi 返回的实体对象没有attributes嵌套层级,字段值直接挂载在实体对象下。查找类型字段返回值为数组结构,单值查找需取数组第一项获取id、name、entityType属性。
  • 缺少非空校验:未判断查找字段是否有值就直接读取属性,字段为空时会抛出未定义异常。
  • 变量声明不规范:category2text未声明就直接赋值,会隐式创建全局变量,存在作用域异常风险。
  • 可选检查:FetchXml 中原排序字段为ava_category1,但查询列中仅包含category1,需确认字段逻辑名是否一致,避免排序报错。

修复后代码

var fetchxml = `
<fetch distinct='false' mapping="logical" output-format="xml-platform" version="1.0">
  <entity name="categorization">
    <attribute name="categorizationid"/>
    <attribute name="name"/>
    <attribute name="category1"/>
    <attribute name="category2"/>
    <attribute name="category3"/>
    <order descending="false" attribute="category1"/> <!-- 可根据实际字段逻辑名调整 -->
    <filter type="and">
      <condition attribute="statecode" operator="eq" value="0" />
    </filter>
  </entity>
</fetch>`;

fetchxml = "?fetchXml=" + encodeURIComponent(fetchxml);

Xrm.WebApi.retrieveMultipleRecords("categorization", fetchxml).then(
  function success(results) {
    var data = [];
    // 遍历entities数组获取实体数据
    for (var i = 0; i < results.entities.length; i++) {
      var record = results.entities[i];
      var category1text = null, category1lookup = null;
      var category2text = null, category2lookup = null;
      var category3text = null, category3lookup = null;
      
      // 非空判断后读取查找字段
      if (record.category1?.length > 0) {
        category1text = record.category1[0].name;
        category1lookup = record.category1[0].id;
      }
      if (record.category2?.length > 0) {
        category2text = record.category2[0].name;
        category2lookup = record.category2[0].id;
      }
      if (record.category3?.length > 0) {
        category3text = record.category3[0].name;
        category3lookup = record.category3[0].id;
      }
      // 将处理后的数据推入数组
      data.push({
        category1text, category1lookup,
        category2text, category2lookup,
        category3text, category3lookup
      });
    }
  },
  function (error) {
    console.log('查询失败:', error.message);
  }
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:06:03