function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
tgk1tgk1 

Update Picklist Field on Account based off of User Record Field

Hey guys-

I need to create a trigger on the account object that does the following:

  • Look at the Account Owner’s User Record
  • Look at the “Region” field on the User Record
  • Update the “Apex Region” field on the Account Object based on the Region value from the User’s Record

 

I have a similar trigger that works perfectly for a text field, but I would like to set this up as a picklist (for easier reporting).

 

Here’s the code that I'm trying (it complies but doesn't update the picklist)-

 

 

trigger ApexTestTrigger on Account (before insert, before update) {

// create a set of all the unique ownerIds  
       Set<Id> ownerIds = new Set<Id>();  
       for (Account a : Trigger.new)  
           ownerIds.add(a.OwnerId);      
     
    // query for all the User records for the unique userIds in the records  
       // create a map for a lookup / hash table for the user info  
       Map<Id, User> owners = new Map<Id, User>([Select Region__c from User Where Id in 
       :ownerIds]);     
     
       // iterate over the list of records being processed in the trigger and  
      // set the Region before being inserted or updated  
      for (Account a : Trigger.new)  
           a.Apex_Region__c = owners.get(a.OwnerId).Region__c;   
}

 Help would be greatly appreciated!

 

ca_peterson_oldca_peterson_old

One thing I can think of is that the ownerId might not be filled before insert - it's defaulted to the current user in this case, and that might be causing it to not detect an owner on records in an insert context, but I don't believe that defaulting happens until after insert.

 

Other than that the code looks good to me. Does it work properly in update transactions? If so you might want to explicitly set the ownerId to the current user if it's null inside the first for loop to make it run properly.