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
Collaborative eCollaborative e 

Pass Account Owner Info to Account Object

I need to pass the Account Owner's phone number to a custom field on the account object. Is there a simple way or code clip?
Best Answer chosen by Admin (Salesforce Developers) 
aalbertaalbert

You could write an apex trigger to identify when the owner is changed, retrieve the owner's phone and set a custom field with that phone number value. Here is some sample code to get you started...

 

 

trigger enter_trigger_name_here on Account (before insert, before update) { List<Id> ownerIds = new List<Id>{}; for(Integer a= 0; a<Trigger.new.size(); a++){ if(Trigger.isUpdate && Trigger.old[a].OwnerId!=Trigger.new[a].OwnerId ) ownerIds.add(Trigger.new[a].OwnerId); else ownerIds.add(Trigger.new[a].OwnerId); } Map<Id, User> users = new Map<Id,User>([select id, phone from user where id in :ownerIds]); for(Integer a= 0; a<Trigger.new.size(); a++){ if(users.get(Trigger.new[a].OwnerId) != null){ Trigger.new[a].custom_phone_field__c = users.get(Trigger.new[a].OwnerId).phone; } } }

 

 

 

All Answers

aalbertaalbert

You could write an apex trigger to identify when the owner is changed, retrieve the owner's phone and set a custom field with that phone number value. Here is some sample code to get you started...

 

 

trigger enter_trigger_name_here on Account (before insert, before update) { List<Id> ownerIds = new List<Id>{}; for(Integer a= 0; a<Trigger.new.size(); a++){ if(Trigger.isUpdate && Trigger.old[a].OwnerId!=Trigger.new[a].OwnerId ) ownerIds.add(Trigger.new[a].OwnerId); else ownerIds.add(Trigger.new[a].OwnerId); } Map<Id, User> users = new Map<Id,User>([select id, phone from user where id in :ownerIds]); for(Integer a= 0; a<Trigger.new.size(); a++){ if(users.get(Trigger.new[a].OwnerId) != null){ Trigger.new[a].custom_phone_field__c = users.get(Trigger.new[a].OwnerId).phone; } } }

 

 

 

This was selected as the best answer
Collaborative eCollaborative e
Thanks for the start. Worked perfectly.
Collaborative eCollaborative e
How do I write and where do I put the test methods that will be necessary to push this to the live Org?
aalbertaalbert
The best place to start for Test Methods is here.