Add Active Admin Users to Group

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;
                              }
             }
}

Want to Apply As Content Writer?

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart

Let's get you started!

Interested in writing Salesforce Content?

Fill in this form and we will get in touch with you :)