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
Allen2Allen2 

help me to write a trigger for one scenario...

We have two lookup field on user object manager and oManager... so the scenario is for the oManager != null, if  oManager is not changed and not equal to manager then it should update the manager field as whatever value we are enterling in the lookup field oManager
and 
if anytime updating the manager name then it should auto reflect to oManager also.......

please help me to write the trigger for this scenario...
I was always confused to write the trigger... but I think it should be before insert and before update....
 
Natarajan _Periyasamy__cNatarajan _Periyasamy__c
trigger UserTrigger on User (Before Insert, Before Update) {
    
    for(User thisUser : Trigger.New) {
        //Logic 1 -  oManager != null, if oManager is not changed and not equal to manager
        if((thisUser.oManager != null && Trigger.IsInsert) 
        || (Trigger.IsUpdate && thisUser.oManager != null && Trigger.OldMap.get(thisUser.Id).oManager == thisUser.oManager
            && thisUser.oManager != thisUser.Manager)) {
            thisUser.Manager = thisUser.oManager;
        }
        //Logic 2
        if(Trigger.IsUpdate && thisUser.Manager != null && Trigger.OldMap.get(thisUser.Id).Manager != thisUser.Manager)) {
            thisUser.oManager = thisUser.Manager;
        }
    }    
}

//Sample Code, you might need to update the same with proper API names for the fields that you intend to use