[英]Apex Trigger to auto populate look up field for multiple records
I am trying to update a lookup field(Benefit_ID in Customer object) with the below code, The code works fine for single record but it is failing for multiple records: 我正在尝试使用以下代码更新查找字段(“客户”对象中的“ Benefit_ID”),该代码对单个记录有效,但对多个记录却失败:
Error: "caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, " 错误:“由于:System.DmlException:插入失败。第0行出现第一个异常;第一个错误:CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY,”
trigger updatelookupfield_Customer on Customer__c (before insert,before update) {
Set<String> Bundle = new Set<String>();
for (Customer__c Cust : Trigger.new) {
Bundle.add(Cust.Bundle__c);
}
List<Benfit__c> BenfitList = [SELECT id, Bundle__c FROM Benfit__c WHERE Bundle__c IN :Bundle];
Map<String, Benfit__c> shippingNumToContactMap = new Map<String, Benfit__c>();
for (Benfit__c c : BenfitList) {
shippingNumToContactMap.put(c.Bundle__c, c);
}
for (Customer__c o : Trigger.new) {
if (o.Bundle__c != null) {
o.Benefit_ID__c = shippingNumToContactMap.get(o.Bundle__c).id;
}
else {
o.Benefit_ID__c = null;
}
}
}
it seems that issue will be on line o.Benefit_ID__c = shippingNumToContactMap.get(o.Bundle__c).id; 看来问题将在o.Benefit_ID__c = shippingNumToContactMap.get(o.Bundle__c).id上; you are trying to get a value from a map with a key, but you are not checking if the key is present in the map.
您正在尝试通过键从映射中获取值,但您没有检查该键是否存在于映射中。
try to add check that the key is in the map before trying to get a value for it. 尝试添加密钥,然后再尝试获取它的值。
trigger updatelookupfield_Customer on Customer__c (before insert,before update) {
Set<String> Bundle = new Set<String>();
for (Customer__c Cust : Trigger.new) {
Bundle.add(Cust.Bundle__c);
}
List<Benfit__c> BenfitList = [SELECT id, Bundle__c FROM Benfit__c WHERE Bundle__c IN :Bundle];
Map<String, Benfit__c> shippingNumToContactMap = new Map<String, Benfit__c>();
for (Benfit__c c : BenfitList) {
shippingNumToContactMap.put(c.Bundle__c, c);
}
for (Customer__c o : Trigger.new) {
if (o.Bundle__c != null && shippingNumToContactMap.containsKey(o.Bundle__c)) {
o.Benefit_ID__c = shippingNumToContactMap.get(o.Bundle__c).id;
}
else {
o.Benefit_ID__c = null;
}
}
}
Svata 斯瓦塔
It doesn't seem to me as though you actually need any Apex here. 在我看来,您似乎实际上并不需要任何Apex。
So there's a Text field on Customer called Bundle__c. 因此,客户上有一个名为Bundle__c的文本字段。
You also have a custom object called Benfit__c which also has a string field called Bundle__c. 您还具有一个名为Benfit__c的自定义对象,该对象还具有一个名为Bundle__c的字符串字段。
You're using the Bundle__c field on Customer to work out which Benfit__c applies to them. 您正在使用客户上的Bundle__c字段来确定哪些Benfit__c适用于他们。
Why can't you have a straight lookup from Customer to Benfit__c? 为什么不能直接从客户查找Benfit__c?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.