获取Lookup对象值时报错lookupObject.getValue is not a function的问询
排查lookupObject.getValue() is not a function错误的原因及解决方法
可能的原因
- 属性逻辑名拼写错误:传入
getAttribute的"attributename"如果不是字段的逻辑名(比如写成显示名、大小写错误、拼写失误),会导致返回null,而null没有getValue方法,直接调用就会抛出该错误。 - formContext对象无效:如果获取
formContext的方式不正确(比如仍使用已废弃的Xrm.Page,或未通过执行上下文正确获取),会导致getAttribute无法返回合法的Attribute对象。 - 目标字段非Lookup类型:若字段是文本、选项集等非Lookup类型,虽大部分字段类型的Attribute对象都有
getValue方法,但类型不匹配时也可能触发异常(这种情况相对少见)。
解决方法
确认字段逻辑名
登录Dynamics 365,进入解决方案找到对应字段,查看它的逻辑名(不要用显示名,逻辑名通常为小写加下划线格式),将代码里的"attributename"替换为正确的逻辑名。确保formContext获取正确
表单脚本必须通过执行上下文获取formContext,禁止使用已废弃的Xrm.Page。示例代码:function yourFunctionName(executionContext) { var formContext = executionContext.getFormContext(); var lookupObject = formContext.getAttribute("your_lookup_field_logical_name"); // 后续逻辑处理 }同时要在表单事件绑定中勾选"传递执行上下文"选项。
增加空值校验
调用getValue前先判断lookupObject是否存在,避免空对象调用方法报错。完整示例:function getLookupValue(executionContext) { var formContext = executionContext.getFormContext(); var lookupObject = formContext.getAttribute("your_lookup_field_logical_name"); if (lookupObject) { var selectedRecord = lookupObject.getValue(); // Lookup的getValue返回数组,需判断是否有选中项 if (selectedRecord && selectedRecord.length > 0) { var recordId = selectedRecord[0].id.replace("{", "").replace("}", ""); // 去除ID的大括号 var recordName = selectedRecord[0].name; var entityType = selectedRecord[0].entityType; // 处理选中记录的数据 } else { console.log("未选中任何Lookup记录"); } } else { console.log("找不到指定的Lookup字段"); } }验证字段类型
进入字段设置页面确认目标字段确实是Lookup类型,若为其他类型,需使用对应类型的取值方式(比如文本字段直接用getValue()返回字符串,选项集返回选项对象)。
内容的提问来源于stack exchange,提问作者SristiJain
相关产品推荐
相关产品推荐

