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
Shawna.ax1585Shawna.ax1585 

Trigger to Update Opp owners Manager on the Opportunity Record

I'm trying to pull the Managers NAME (not ID) of the opportunity owner and display it on the opportunity record.  I was able to do this by copying the below trigger someone else had posted.  It works great but I want the manager "time stamped" meaning, I don't want the managers name to be updated if it happens to change.  I only want the field to display the manager of the opp owner at the time the opp was created. 

 

How can I do this??

********************************************************

 

trigger UpdateOwnerManager on Opportunity (before insert, before update ){
  /**
  1. For each opportunity being inserted add User Id value in in Set of User Ids.
  2. Fetch all Users whose Id is in the Set.
  3. Add these fetched Users in a Map <User Id, User object>
  4. for each opportunity being inserted get User from the map and update the field values  
  **/  
 
  //holds User Ids
  Set<Id> setUserIds = new Set<Id>();
 
  //holds a list of Users
  List<User> lstUser = new List<User>();
 
  //holds key value pairs of User Id and User Object
  Map<Id, User> mapUserObj = new Map<Id, User>();

  //holds User object
  User UserObj;
   
  //For each opportunity being inserted add User Id value in in Set of User Ids.
  for(Opportunity oppObj : Trigger.new){
    if(oppObj.OwnerId != null){
      setUserIds.add(oppObj.OwnerId);
    }
  }
 
  //Fetch all Users whose Id is in the Set.
  lstUser = [select Id, Name, ManagerId from User where Id in :setUserIds Limit 1000];
  if(lstUser.size() == 0){
    return;  
  }
 
  //Add these fetched Users in a Map <User Id, User object>
  for(User usrObj : lstUser){
    mapUserObj.put(usrObj.Id, usrObj);  
  }
 
  //for each opportunity being inserted get User from the map and update the field values
  for(Opportunity oppObj : Trigger.new){
    //get User object
    if(oppObj.OwnerId != null){
      if(mapUserObj.containsKey(oppObj.OwnerId)){
        UserObj = mapUserObj.get(oppObj.OwnerId);
        //map opportunity fields to User fields
        oppObj.Opportunity_Owner_s_Manager__c = UserObj.ManagerId;
      }  
    }
  }
}

 

Vishal KashyapVishal Kashyap

Salesforce tracks the change in field history tracking.

 

Moreover if you want to implement your logic, create another field and apply a triger which copied the name of the opp creater when opportunity is created. In this way you can always know who was the real creator of the opportunity.

 

Hope you got some clue.

Jeff MayJeff May

You can also use your existing trigger, but only do the Manager update if the trigger.IsInsert.

 

Success,

 

JeffM