2

New to apex and have a question about writing triggers. Essentially, I'm trying to create a trigger that updates a given field when another field is updated (after a record is created/inserted into Salesforce).

More specifically, when a custom Account lookup field (lookup value is a custom object record) is updated, it should update another field with a different value from the custom object record.

i.e. When I update the High School name to Elm High School, it will also update the yield associated with that high school.

Below is the code that I've created so far:

trigger UpdateYield on Account (before update) {
Set<String> HS = new Set<String>();
for (Account hsName : Trigger.new) {
    if (hsName.High_School_LU__c != null) {
        HS.add(hsName.High_School_LU__c);
}

List<High_School__c> y = [SELECT Name, Yield__c FROM High_School__c WHERE Name IN :HS];

Map<String, High_School__c> yLU = new Map<String, High_School__c>();
for (High_School__c h : y) {            
    yLU.put(h.Name, h);    
}

for (Account YieldU : Trigger.new) {
    if (YieldU.High_School_LU__c != null) {
        High_School__c a = yLU.get(YieldU.Name);
        if (a != null) {
            YieldU.Yield__c = a.Yield__c;
        }
    }        
}
}
}

It saves however, it still does not work when I update the field.

Any help would be greatly appreciated. Thanks in advance.

4

1 回答 1

2

这里的问题是查找字段的值实际上不是字符串(如 UI 中显示的那样)而是 ID,因此当您执行 SOQL 查询时,您将 ID 与 Name 字段进行比较并且没有得到任何结果。

如果您将代码更改为以下内容,您应该会得到您期望的结果。

还应该通知这个简单的用例也可以使用简单的工作流字段更新而不是触发器来完成。

trigger UpdateYield on Account (before update) 
{
    Set<Id> HS = new Set<Id>();

    for (Account hsName : Trigger.new)
    {
        if (hsName.High_School_LU__c != null)
        {
            HS.add(hsName.High_School_LU__c);
        }
    }

    Map<Id, High_School__c> y = [SELECT Name, Yield__c FROM High_School__c WHERE Id IN :HS];

    for (Account YieldU : Trigger.new)
    {
        High_School__c a = y.get(YieldU.High_School_LU__c);
         if (a != null) 
         {
               YieldU.Yield__c = a.Yield__c;
         }
     }        
 }
于 2014-03-06T23:17:05.210 回答