我写了一个触发器,将帐户所有者名称放在为该帐户创建的案例中。它在200的批量测试中也能正常工作。以下是代码:
trigger CaseBeforeInsertUpdate on Case (before insert, before update) {
Set<Id> accountIds = new Set<Id>();
Set<Id> accountOwnerIds = new Set<Id>();
for (Case c : Trigger.new) {
if(c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id,Account> accountMap = new Map<Id, Account>([select Id, OwnerId from Account where Id IN :accountIds]);
for (Account a : accountMap.values()) {
if(a.OwnerId != null) {
accountOwnerIds.add(a.OwnerId);
}
}
Map<Id, User> userMap = new Map<Id,User>([select Name from User where Id IN :accountOwnerIds]);
if(userMap.size() > 0) {
for(Case c: Trigger.new) {
c.MerchantOwner__c = userMap.get(accountMap.get(c.AccountId).OwnerId).name;
}
}
}
偶然我发现了一个错误,我无法弄清楚出了什么问题。如果我转到案例列表视图(即我的打开案例)并选择多个案例并关闭它们,我会收到一个错误:System.NullPointerException:尝试取消引用更新MerchantOwner字段的行的空对象。当我在我的测试类中大量关闭案例时,一切正常......
我最好的猜测是我正在尝试为没有帐号的案例执行此操作,但据我所知,我尝试不将这些案例更新为不将其添加到accountIds首先设置
有谁知道我做错了什么?任何帮助将不胜感激。
答案 0 :(得分:1)
我会改变以下For循环:
for(Case c: Trigger.new) {
c.MerchantOwner__c = userMap.get(accountMap.get(c.AccountId).OwnerId).name;
}
要
for(Case c: Trigger.new) {
if (c.AccountId != null // Make sure there is an Account linked to the Case
&& accountMap.ContainsKey(c.AccountId) // Make sure our Account query captured it
&& accountMap.get(c.AccountId).OwnerId != null // Make sure that account has an owner
&& usermap.ContainsKey(accountMap.get(c.AccountId).Ownerid) // Finally make sure our User query found the owner
){
c.MerchantOwner__c = userMap.get(accountMap.get(c.AccountId).OwnerId).name;
}
}