+ Start a Discussion
SFDC Apex DevSFDC Apex Dev 

written a trigger below.. but one of the condition I m not able to satisfy.. please help to correct it..

In this trigger, I am populating the custom field oManager from the standard field Manager and vice-versa... but I need to do one more thing.. if the oManager is null, it should reflect the null value in Manager field also... I tried but that time because of for loop it is not letting me to complete the logic 2.....

APEX TRIGGER
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;
        }
    }    
}
Hemant_SoniHemant_Soni
Hi,
Please try Below Code.
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(Trigger.IsInsert || Trigger.IsUpdate){
			if( thisUser.oManager != null && thisUser.oManager != thisUser.Manager && (Trigger.OldMap == null || (Trigger.OldMap != null && thisUser.oManager != Trigger.OldMap.get(thisUser.Id).oManager))){
				thisUser.Manager = thisUser.oManager;
			}else if(thisUser.oManager == null){
				thisUser.Manager = 'NULL';
			}
		}
    }    
}
Thanks
Hemant