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
cased1919cased1919 

Update User Manager Field based on value of text field.

I have two custom fields in the user object.
1) EmployeeId (Unique Text field and provided by Human Resources system)
2) Manager Emp Id (not unique since this id would be on multiple users records, Text field also provied by HR system)

The HR system does not store SF user Ids, so what I need to do is update the Standard Salesfoce Manager field if the users Manager_Emp_Id is populated.


So if employee record for John Doe has a value in the Manager Emp Id field, the trigger needs to query the user object and look for a EmployeeId that matches that Manager Emp Id. It also needs to update the Standard Manager field anytime there is an update (new manager).

The logic seems to be straight foward, but for some reason I keep hitting walls. This is my latest attempt (still a newbe at this).

The error I'm receieving is "Loop must iterate over a collection type: SOBJECT:User"

trigger UpdateMangerName on User (before insert, before update) {
    List<String> NewManEmpIds = new List<String>();   
    for (User u : Trigger.new[0]) {
        NewManEmpIds.add(u.Manager_Emp_Id__c);
    }
    
    List<User> NewManId = [SELECT Id from User WHERE Employee_Number__c = :NewManEmpIds];
    
    Map<String, Id> ManagerId = new Map<String, Id>();
    for (User u : NewManId) {
        ManagerId.put(u.id);
    }
    
    for (User u : Trigger.New[0]){
            //check if the Manager Emp Id is changed and if it is different from the current manager
            if (u.Manager_Emp_Id__c != Trigger.oldMap.get(u.Id).Manager_Emp_Id__c
             && NewManId != u.ManagerId) {
                u.ManagerId = NewManId;
            }
            
        }
}

 Thanks for your help.

 

Navatar_DbSupNavatar_DbSup

Hi,

 

 Something is wrong with the trigger code. some changes which are given below in your trigger code.

 

     for(User u: trigger.new)  // Replace trigger.new[0] with trigger.new

     {

        NewManEmpIds.add(u.Manager_Emp_Id__c);

     }

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved.