+ Start a Discussion
Chamil MadusankaChamil Madusanka 

Add users into a Queue i apex code

Hi All,


How can we add users into an existing Queue or newly created (in apex code) Queue in apex code?

Then I want to use that queue for an approval process which also created in apex code. How can I resolve this issue?



Thanks in Advance

Same requirement, here Hope someone clarifies about this .... 
Austin DelormeAustin Delorme

Salesforce stores users in groups as a GroupMember object, so you can insert records of these to add users to a group.


//This can be replaced with any user id
Id userId = UserInfo.getUserId();

//Get the group you want. Queues are stored as group objects with a type of Queue
Group g = [select Id from Group where Name='My Group Name' AND Type = 'Queue'];

GroupMember member = new GroupMember();
member.UserOrGroupId = userId;
member.GroupId = g.Id;

insert member;


Thanks Austin ! Can you also tell how does this work ? I mean the inclusion of a User in a Group is via GroupMember records ; why was it not something like a User having a lookup to a Group, is there something that I am missing ?

In both cases any user can be under any group and a user can be under more than one group right?

Austin DelormeAustin Delorme

This is a case of a many-to-many relationship. As you said, users can be associated with multiple groups, and a single group can have multiple members. The way that Salesforce creates many-to-many relationships is through the use of a "junction object" (https://help.salesforce.com/HTViewHelpDoc?id=relationships_manytomany.htm&language=en_US (https://help.salesforce.com/HTViewHelpDoc?id=relationships_manytomany.htm&language=en_US)). In this instance, the GroupMember object acts as this junction object.

The reason it cannot be a lookup on either the Group or User object is because a lookup only allows you a one-to-one relationship, not a many-to-many. Let's say that the lookup to Group is on the User object. This lookup field can lookup to a single Group, so the User can be associated with only one Group. You could add a second field to lookup to a second Group, but what if the user is in three Groups? It would get messy very quickly if you had 100 fields that lookup to a Group on a User, and that still doesn't cover the situation where a User needs to be in 101 Groups. This is why a junction object is needed.

A GroupMember is a record of a relationship between a certain User and a Group (or Queue - Queues are actually Groups with a field called Type marked as "Queue"). If you have a User that needs to be in 10 different  Groups, then you will have 10 different GroupMember records. All of these records will point to the same User, but they will each point to a different Group, creating 10 distinct associations between the User and the Groups.