Salesforce Trigger: Update field Trigger from Custom Object

user3385592 picture user3385592 · Mar 5, 2014 · Viewed 16.2k times · Source

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.

Answer

Alex Tennant picture Alex Tennant · Mar 7, 2014

The problem here is that the value of a lookup field is not actually a string (as displayed in the UI) but an ID, so when you perform your SOQL query you are comparing an ID to the Name field and getting no results.

If you change your code to the following you should get the result you expect.

It should also be notified that this simple use case could also be accomplished using a simple Workflow Field Update rather than a trigger.

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;
         }
     }        
 }