/***************************************************************************** Name : Update Owner Manager on the opportunity from the User object Purpose : defaults the Owner Manager field of the opportunity from the User ******************************************************************************/ 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> listUser = 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. listUser = [Select u.Manager.Email, u.ManagerId From User u]; if(listUser.size() == 0){ return; } //Add these fetched Users in a Map <User Id, User object> for(User usrObj : listUser){ 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.Manager_of_record_owner__c = UserObj.Manager.Email; } } } } |