+ Start a Discussion
Sunil Kumar 81Sunil Kumar 81 

Trigger to update User Team.

Hi,

I have created a custom field on User i.e. My_Team__c . So I want to create a trigger on- when create or update a user its manager,s My Team will be automaticall updated with new created user Name and its subusers.. So if any one know how to do please help.
Shashikant SharmaShashikant Sharma
Definiely its solution is a after insert trigger on User but to give you moore thought I need following information :

1. What is DataType of field My_Team__c is it Text(255)
2. You want to update My_Team__c on the immediate manager for the newly create user  or complete hierarchy of managers above the newly created user 
3. What do you mean by Subusers 
Sunil Kumar 81Sunil Kumar 81
data type of field is Text(255)
I want to update complete hierarchy.which means the user at top level have all other users in his team.
 
gokul bharatigokul bharati
Hi Sunil,

Please find the snippert below.

trigger DontCreateUserRoleBelowManagerRole on User(before insert){
Map<Id,Id> RoleIDParentID=new Map<Id,Id>();
Map<Id,Id> managerIDRoleID=new Map<Id,Id>();
for(UserRole a:[select id,parentRoleID from UserRole]){
if(a.parentRoleID!=null){
RoleIDParentID.put(a.id,a.parentRoleID);
}
}
for(User a:[select id,UserRoleId from user]){
managerIDRoleID.put(a.id,a.UserRoleID);
}
if(Trigger.IsBefore&&Trigger.IsInsert){
 for(User a:Trigger.new){
 if(a.UserRoleID==managerIDRoleID.get(a.ManagerId)){
 a.addError('Manger Role and User role cant be same');
 }
 if(RoleIDParentID.get(a.UserRoleID)!=managerIDRoleID.get(a.managerId)){
 a.addError('User Role should be below Manager role');
 }
 for(User b:[select id,ManagerId,Name from User where ManagerId=:a.managerID]){
 if(b!=null){
 a.MyTeam__c+=b.Name;
 }
 }
 }
 }
}

P.S. If this answers you question, please mark it as "Best Answer" so it will help other community members too.

Thanks,
Gokul