javascript - 如何忽略 CRM 查找字段中的 NULL 值?
问题描述
每当关联帐户被标记为“服务观察”时,我有以下代码设置 onLoad 以在“发货”记录上生成横幅。该代码当前可以运行,但是它正在生成错误警报"unable to get property '0' of undefined or null reference"
。当用户创建一个新的 Shipment 记录时会发生此错误,因为 Account 字段还没有值。
如何配置代码以忽略 Account 字段中的 NULL 值?
function checkServiceWatch() {
try{
var account = Xrm.Page.getAttribute("cmm_account").getValue();
var accountid = account[0].id;
var formattedGuid = accountid.replace("}", "");
accountid = formattedGuid.replace("{", "");
// alert("Accountid: " + accountid); // does that ID have brackets around it?
// alert("Request: " + Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountid + ")?$select=cmm_servicewatch");
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts(" + accountid + ")?$select=cmm_servicewatch", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function()
{
if (this.readyState === 4)
{
req.onreadystatechange = null;
if (this.status === 200)
{
var result = JSON.parse(this.response);
var serviceWatch = result["cmm_servicewatch"];
// alert("serviceWatch: " + serviceWatch);
if(serviceWatch) //set notification
{
Xrm.Page.ui.setFormNotification("This Account is currently under Service Watch","WARNING","1");
} // else
// {
// //Xrm.Page.ui.clearFormNotification("1");
// }
}
else
{
Xrm.Utility.alertDialog("Status: " + this.status + ", Text: " + this.statusText);
}
}
};
req.send();
}
catch (err) {
alert("ServiceWatchCheckRibbon | checkServiceWatch " + err.message);
}
}
应忽略正在创建的记录,但在现有货件上生成带有帐户值的横幅。
解决方案
假设account将持有一个数组并且account id 不为 0
您可以使用长度属性来检查帐户是否存在。如果是,则继续,否则您可以返回
var account = Xrm.Page.getAttribute("cmm_account").getValue();
var accountid = account.length && account[0].id;
if(!accountid) 返回;
如果存在,此行将返回id到 accountid 否则返回0
var accountid = account.length && account[0].id;
如果您不确定帐户的第一个元素 ( account[0] )中是否存在id ,您还可以添加额外的检查,方法是添加
var accountid = account.length && (account[0] || {}).id;
如果您的帐户变量中有没有键ID的元素,这将返回未定义
只有当帐户存在时accountid变量才会保存帐户 ID,否则它将有 0 或未定义,如果您愿意继续,可以相应地处理。
如果我解决了您的问题,请告诉我。
推荐阅读
- javascript - ngRepeat:dupes 在数组中输入空值时出错
- pandas - 根据 Pandas 中数据框列的现有值递增或重置计数器
- c++ - 将参数的省略复制为返回值
- reactjs - this.state 在 api 调用后给出 null
- java - Docker 容器中的 Wildfly 未启动
- sql - 创建 Postgres 视图出现错误:列“id”指定了多次
- java - 在 actionListener 中获得 JTextFeild 的引用
- javascript - 如何在javascript中检测光标与多个移动对象的碰撞?
- python - 在 Python 中解析简历中的技能部分
- php - 使用 Telegram Bot API 制作注册机器人