Assigning Group User from Apex

Assigning Group User from Apex

Public Groups in Salesforce.com serve as a useful tool to share content in an environment with multiple users. In our projects at M&S, we have used public groups in a variety of capacities including assigning users to records based on record criteria. In this post, we’d like to show you the benefit of using public groups for users outside of the traditional Salesforce assignment.

One useful aspect of Public Groups is that you can manipulate the group without effecting custom code. For example:

If you have a line of code similar to the following:

String userId = UserInfo.getUserId();

User u = [SELECT Id from User where lastname = ‘Smith’];

Case c = new Case();
c.OwnerId = userId;
c.Manager__c = u.Id;
insert c;

With this logic, when a Case is created, the custom field, Manager, will be set to the User ‘Smith’. If this user becomes deactivated, you will hit a DML error on the trigger or class stating an inactive user. However, if you would implement the Public Group, you can avoid this issue, and assign a group with the Manager in it, thus allowing an administrator to update the group if company members would change.

To use the Public Group, you will need to do the following:

//First query the Group Object for the Manager Group.

g = [Select Id from Group where Name =:’Manager Group’];

//Within this Group the User Id for ‘Smith’ we be contained, query the GroupMember Object to find the UserOrGroupId.

gm = [Select GroupId, UserOrGroupId from GroupMember where GroupId =:g.Id];

 

Now you can include the User ‘Smith’ in your code:

g = [Select Id from Group where Name =:’Manager Group’];
gm = [Select GroupId, UserOrGroupId from GroupMember where GroupId =:g.Id];

String userId = UserInfo.getUserId();

Case c = new Case();
c.OwnerId = userId;
c.Manager__c = gm.UserOrGroupId;
insert c;

Leave a Reply

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