4

Is it possible to add a Group to another Group (as Sub/Nested Group) through Apex - Trigger/Batch?. Also want to know the possibility to add a Role into a Group.

Any thoughts ??

6

You can use the GroupMember object for this. A GroupMember can either be a User or a Group. https://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_groupmember.htm

Group parentGroup = [Select Id From Group Where Name = 'ParentGroupName'];
Group childGroup = [Select Id From Group Where Name = 'ChildGroupName'];
GroupMember gm = new GroupMember(GroupId = parentGroup.Id, UserOrGroupId = childGroup.Id);
insert gm;

To add a role into a Group via APEX, use the automatically created Group for the Role (a Group with Type 'Role' and relatedId = roleId). Then add the Group as a GroupMember to the parent Group.

UserRole theRole = [Select Id From UserRole Where Name = 'theRoleName';
Group roleGroup = [Select Id, Name, Type From Group Where Type = 'Role' AND relatedId = :theRole.Id];
GroupMember gm = new GroupMember(GroupId = parentGroup.Id, UserOrGroupId = roleGroup.Id);
insert gm;
|improve this answer|||||
  • Getting message- Group.RelatedId not Writable -when inserting Group with Type Role. Please suggest!! – Sunil Sharma Oct 16 '14 at 12:08
  • Any suggestions on this? – Sunil Sharma Oct 16 '14 at 12:12
  • How to insert a group through apex with type Role and related Id of a role? – Sunil Sharma Oct 16 '14 at 12:15
  • Yes, sorry I forgot that the role-group is automatically created whenever you create a role. Actually there are multiple groups created for each role: 'Role' 'RoleAndSubordinates', 'RoleAndInteralSubordinates' etc, depending on whether you have portals/communities. I updated my answer with this. – Guy Clairbois Oct 16 '14 at 12:18
  • Really? You can add a group as a sub group using Apex? I thought a group couldn't be added to another group, but you're saying it can be done through Apex? It could be that I'm just behind on some of the platform updates of the last year, so wanted the clarification. – crmprogdev Oct 16 '14 at 14:43

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.