案例触发器失败时的Salesforce帐户所有者名称
我编写了一个触发器,将帐户所有者的名称放在为该帐户创建的案例上。它在我200的批量测试中工作并执行。代码如下:案例触发器失败时的Salesforce帐户所有者名称,salesforce,apex-code,Salesforce,Apex Code,我编写了一个触发器,将帐户所有者的名称放在为该帐户创建的案例上。它在我200的批量测试中工作并执行。代码如下: trigger CaseBeforeInsertUpdate on Case (before insert, before update) { Set<Id> accountIds = new Set<Id>(); Set<Id> accountOwnerIds = new Set<Id>(); for (Case
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;
}
}
}
在插入前触发案例更新案例(插入前、更新前){
Set accountIds=new Set();
Set accountOwnerIds=new Set();
对于(案例c:触发器。新建){
如果(c.AccountId!=null){
AccountId.add(c.AccountId);
}
}
Map accountMap=新映射([从Id所在的帐户中选择Id、OwnerId:AccountID]);
对于(帐户a:accountMap.values()){
如果(a.OwnerId!=null){
accountownerId.add(a.OwnerId);
}
}
Map userMap=新映射([从用户中选择名称,其中Id位于:accountOwnerIds]);
如果(userMap.size()>0){
对于(案例c:Trigger.new){
c、 MerchantOwner\uuu c=userMap.get(accountMap.get(c.AccountId.OwnerId).name;
}
}
}
我偶然发现了一个bug,但我不知道出了什么问题。如果转到案例列表视图(即打开的案例)并选择多个案例并关闭它们,则会出现错误:System.NullPointerException:尝试为更新MerchantTowner字段的行取消引用null对象。当我在我的testclass中批量关闭案例时,一切都很好
我最好的猜测是,我正在尝试对一个没有附加帐户的案例执行此操作,但就我所见,我试图通过不首先将这些案例添加到AccountID集来不更新这些案例
有人知道我做错了什么吗?非常感谢您的帮助。我将以下For循环更改为:
for(Case c: Trigger.new) {
c.MerchantOwner__c = userMap.get(accountMap.get(c.AccountId).OwnerId).name;
}
到
在通过ListView批量更改所有权时,似乎也会发生这种情况。如何在答案中设置代码格式。。。无论如何,我昨晚把代码改成:
for(Case c:Trigger.new){if(accountMap.containsKey(c.AccountId)){accounta=accountMap.get(c.AccountId);if(userMap.containsKey(a.OwnerId)){c.MerchantOwner\u c=userMap.get(a.OwnerId.name;}}
这似乎与您建议的方式相同,或者您是否看到任何差异?撇开编程风格和可读性不谈,它们在功能上应该是相同的。您没有检查案例以确保它链接到帐户(使AccountId为null),但是accountMap不应该有null键,因此不会产生任何影响。出于好奇,为什么要创建实例帐户a而不是实例用户u?
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;
}
}