In the hypothetical situation, I have 100 queues, if I needed to update half of my Queues to have a member of Role 1 and Subordinates and the other 50 queues to have a member of Role 2 and subordinates, could this be accomplished via Apex or DataLoader?

I reviewed the similar question below, but the answers only address assigning individual users to a queue via apex, not by role / roles and subordinates.

Assigning Users or Role to queue via apex code


Yes, you can query for a Group that matches on Role or RoleAndSubordinates, and insert a GroupMember record for the given queue (also a Group).

Group[] queues = [select id from group where type='queue'];
Group[] roles = [select id from group where type='RoleAndSubordinates'];
GroupMember[] newMembers = new GroupMember[0];
for(integer i = 0, r = roles.size(), s = queues.size(); i < s; i++) {
  newMembers.add(new GroupMember(
    UserOrGroupId=roles[Math.mod(i, r)].Id
insert newMembers;

Or whatever it is you're trying to do. Just query, build a new list of values, and insert.

  • This will do it! I know this is a separate question and can open a new question if needed, but if I wanted to remove all of the "group members" (roles) from a queue, I would simply query for all GroupMember where GroupId == queue.Id, add those GroupMember(s) to a GroupMember list and use a delete DML statement? – S.B. Aug 21 '18 at 21:12
  • 1
    @S.B. Yes, you can do deletes as well. – sfdcfox Aug 21 '18 at 22:05

Yes this is possible but it takes a little bit of work.

Every role has a group automatically created for it. Knowing this you can use the "userOrGroupId" field on the membership object to set a role as a member of the group.

The group object has a field called relatedId which will point to the role that it's associated with.

ID roleId = 'However you get this id in your code';
Id someGroupId = 'However you get this id in your code';

Group roleGroup = [SELECT Id FROM Group WHERE RelatedId = :roleId];

GroupMember gm = new GroupMember(
    userOrGroupId = roleGroup.Id,
    GroupId = someGroupId

insert gm;

Something like that should work. I minimized the code we use for a similar purposes so I know this can work, you may have to do some playing to fit it into your use case.

  • Okay. I ran your query after manually grabbing the group id provided after opening the role and then clicking that role and subordinates and grabbing the "groupid" from the URL, but it returns two identical ids. – S.B. Aug 21 '18 at 20:56
  • 1
    Use the Type field as explained in SFDCFoxes answer. – gNerb Aug 21 '18 at 21:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.