Skip to main content
3 of 3
Fixing code formatting (and general formatting)
Derek F
  • 64.1k
  • 15
  • 55
  • 104

How to get group ID of the public group?

I tried to add User to the Admins public group whenever a new User is created with system admin profile. But I got the following error :

Apex trigger addAdminToPublicGroup caused an unexpected exception, contact your administrator: addAdminToPublicGroup: execution of AfterInsert caused by: System.QueryException: List has no rows for assignment to SObject: Class.AddAdmin.AddToPublicGroups: line 6, column 1

Group g = [select Id from Group Where DeveloperName = 'Public Group'] doesn't return any row. What should I do to get the group id of the public group?

Code

public class AddAdmin {
 
    public static void AddToPublicGroups(Set<Id> userIds)
    {
        //Get the groups that the user should be added to
        Group g = [select Id from Group Where DeveloperName = 'Public Group'];
        
        List<User> users = [select id from user where id IN :userIds AND Profile.Name = 'System Admin']; 

        List<GroupMember> listGroupMember = new List<GroupMember>();  

        // loop the users that have been created
        for (User user : users) {
            GroupMember gm = new GroupMember(); 
            gm.GroupId = g.id;
            gm.UserOrGroupId = user.id;
            listGroupMember.add(gm);   
        }

        if(listGroupMember.size() > 0)
            insert listGroupMember;
    }
}