+ Start a Discussion
jeffdonthemicjeffdonthemic 

Trigger - Related Object Null?

I have the following trigger that sets a field on the Account based upon the owner's settings. The Owner object appears to be blank during the execution of the trigger?? Running the code from Eclipse, I can see that the Owner is not null and the values should be set properly.

Any idea why the Owner reference is null?

Code:
trigger UpdateBusinessUnit on Account (before insert, before update) {
 
 for (Account a : Trigger.new) {
     
  System.debug('Industry: '+a.Industry__c);   
  System.debug('SubLocation: '+a.Owner.SubLocation__c);  // <----- returned as null—
  System.debug('Location: '+a.Owner.Location__c); // <----- returned as null–
  
  if (a.Industry__c != null && a.Owner.SubLocation__c != null && a.Owner.Location__c != null) {
   // set the value   
   a.Business_Unit__c = a.Industry__c+a.Owner.SubLocation__c+a.Owner.Location__c;
  } else {
   a.Business_Unit__c = '';
  }
  
 }

}

 


sfdcfoxsfdcfox
Ironically, data on related objects are NOT loaded as part of the Trigger. Usually, that means an extra SOQL call:

Code:
Map<Id,Account> a = new Map<Id,Account>([select id,name,owner.firstname,owner.lastname,owner.email,owner.username from account where id in :trigger.newMap.keySet()]);

After doing the trigger, your new map will have the data you are interested in referencing. Or, you could use just a list/array if that's all you're concerned about accessing, but the map makes it a bit nicer in terms of referencing the accounts.
jeffdonthemicjeffdonthemic
Thanks for the feedback. Based upon your comments I have come up with the following solution:
 
Code:
trigger updateBusinessUnit on Account (before insert, before update) {
 
 // create a set of all the unique userIds for all records
    Set<Id> ownerIds = new Set<Id>();
    for (Account acct : Trigger.new)
        ownerIds.add(acct.OwnerId); 
        
    // query for all the User records for the unique userIds so we can search through them by name/value pair  
 Map<Id, User> owners = new Map<Id, User>([Select Name, SubLocation__c, Location__c from User Where Id in :ownerIds]);            
 
 for (Account a : Trigger.new) {
     
  if (a.Industry__c != null && owners.get(a.OwnerId).SubLocation__c != null && owners.get(a.OwnerId).Location__c != null) {
   // set the value   
   a.Business_Unit__c = a.Industry__c+owners.get(a.OwnerId).SubLocation__c+owners.get(a.OwnerId).Location__c;
  } else {
   a.Business_Unit__c = '';
  }
  
 }

}