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
mng0827mng0827 

Specify Users in Account Owner Trigger

Hi,

I have a trigger which displays the account owner's phone and meeting url in the account record. I'd like to apply this trigger only for specific account owners (users) but don't know where to include this criteria in the trigger below:

trigger OwnerDetailsToAccount on Account (before insert, before update) {
    
    Set<id> ownerIds = new Set<id>();
    if (Trigger.isInsert){
    for (Account a : Trigger.new){
        ownerIds.add(a.OwnerId);  
        }
        }
       
        if (Trigger.isUpdate){ 
    for (Account a : Trigger.new){
    for (Account b : Trigger.old){
   if(a.OwnerId != b.OwnerId){
        ownerIds.add(a.OwnerId);  
       }
        }
        }
        }

    Map<id, User> owners = new Map<id, User>([Select FirstName, LastName, Email, Phone, Title, Time_Trade_Client_Meeting_URL__c from User Where Id in :ownerIds]); 

    for (Account a : Trigger.new)
    {
    if(owners.size()>0){
    if(a.OwnerId == owners.get(a.OwnerId).Id)
    {
        a.Owner_Email__c = owners.get(a.OwnerId).Email;
        a.Owner_First_Name__c = owners.get(a.OwnerId).Firstname;
        a.Owner_Last_Name__c = owners.get(a.OwnerId).Lastname;
        a.Owner_Phone__c = owners.get(a.OwnerId).Phone;
        a.Owner_Title__c = owners.get(a.OwnerId).Title;
        a.Owner_Time_Trade_Client_Meeting_URL__c = owners.get(a.OwnerId).Time_Trade_Client_Meeting_URL__c;
  }   
  } 
}
}

I'd like to specify 3 users in this trigger. Can someone help me how to do this?
Thanks!
Ramu_SFDCRamu_SFDC
You can do that by adding a condition in the SOQL query where you are fetching the results to Map field as shown in the bold text below. Also check if the map has the key before comapring the ownerid's

Please find the changes done to your code below (in bold text)


Map<id, User> owners = new Map<id, User>([Select FirstName, LastName, Email, Phone, Title, Time_Trade_Client_Meeting_URL__c from User Where Id in :ownerIds] and <some other condition to get specific users>);

    for (Account a : Trigger.new)
    {
    if(owners.size()>0){
if(owners.containskey(a.ownerid)){  
   if(a.OwnerId == owners.get(a.OwnerId).Id)
    {
        a.Owner_Email__c = owners.get(a.OwnerId).Email;
        a.Owner_First_Name__c = owners.get(a.OwnerId).Firstname;
        a.Owner_Last_Name__c = owners.get(a.OwnerId).Lastname;
        a.Owner_Phone__c = owners.get(a.OwnerId).Phone;
        a.Owner_Title__c = owners.get(a.OwnerId).Title;
        a.Owner_Time_Trade_Client_Meeting_URL__c = owners.get(a.OwnerId).Time_Trade_Client_Meeting_URL__c;
  } //3rd If
 
}// 2nd If
} // 1st If
} // For


Hope this helps