0

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;
    }
}
1
  • I have to create a public group let's say called 'Test' and then use Group g = [select Id from Group Where Name = 'Test']; to retrieve the group information. Nov 6, 2023 at 19:41

2 Answers 2

0

DeveloperName is the API name, so it cannot have a space. If you want to use the group name as you see it in Setup, then you have to use the Name (which is the label) field.

2
  • Thanks for the reply! I used the Group g=[select Id from Group Where Name='Public Group']; I got the same error. Nov 6, 2023 at 18:42
  • Are you sure you have a group named "Public Group"? What if you try selecting a different group, do you get the same error? Nov 6, 2023 at 18:47
0

Public Group Image

Suppose you have the Public group having the Label 'Public Group' and Group Name = 'Public_Group' as shown in image then you need to remove the following statement from your code that is throwing error :

Group g = [select Id from Group Where DeveloperName = 'Public Group'];

and use the following correct statement :

Group g = [select Id from Group Where DeveloperName = 'Public_Group']; 
2
  • Thanks for your reply! I tried it on the Query Editor, it returns zero rows. Nov 6, 2023 at 19:25
  • Ok, so can you once check if the public group having Group Name = Public_Group exists or not ? Nov 6, 2023 at 19:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .