When a new active user with the “System Administrator” profile is created, this trigger automatically adds them to the “Admins” public group, streamlining group membership management.
Explore similar automation examples via this YouTube playlist.
Solution:
trigger UserTrigger on User (after insert) {
if(Trigger.isInsert){
if(Trigger.isAfter){
UserTriggerHandler.addUserToGroup(Trigger.new);
}
}
}
public class UserTriggerHandler{ public static void
addUserToGroup(List<User> usList){
Id systemAdminId= [SELECT Id FROM Profile WHERE
Name=’System Administrator’].Id;
Id groupId=[SELECT Id FROM Group WHERE Name=’Admins’].Id;
List<GroupMember> groupList = new List<GroupMember>();
for(User us : usList){ if(us.ProfileId == systemAdminId
&& us.IsActive){ GroupMember grp= new
GroupMember(); grp.GroupId=groupId;
grp.UserOrGroupId=us.Id; groupList.add(grp);
}
}
if(!groupList.isEmpty()){
insert groupList;
}
}
}