4

It looks like ConnectApi.ChatterGroup is abstract. Is there really no way to create Chatter groups via connect in Apex?

Is the solution to call the chatter REST API from APEX?

UPDATED based on answer below:

 public static Id createGroup(String groupName, List<User> users) {

    CollaborationGroup g = new CollaborationGroup(Name=groupName, CollaborationType='Public');
    g.OwnerId = UserInfo.getUserId() ;
    insert g;

    List<CollaborationGroupMember> groupMembers = new List<CollaborationGroupMember>();

    for (User user: users) {
        CollaborationGroupMember member = new CollaborationGroupMember();
        member.MemberId = user.Id ;
        member.CollaborationGroupId = g.Id ;
        groupMembers.add(member);
    }

    insert groupMembers;
    return g.Id ;
}
1
  • CollaborationRole column in CollaborationGroupMember object needs to be filled with Standard / Admin value Commented Apr 11, 2018 at 7:49

2 Answers 2

10

No need for connectapi to create a chatter group. You can created it directly e.g.:

CollaborationGroup myGroup = new CollaborationGroup();
myGroup.Name='My Group';
myGroup.CollaborationType='Public'; //can be 'Public' or 'Private'                   
insert myGroup;

Then to add a member:

CollaborationGroupMember groupMember = new CollaborationGroupMember();
groupMember.memberid = userId; //id of User you wish to add
groupMember.CollaborationGroupId = myGroup.Id; //Id of group created above
insert groupMember; 
2
  • When i try to do it in code directly like you suggested im getting and error on adding member. System.DmlException: Upsert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Entity is read-only: CollaborationGroupMember: [] Commented Feb 7, 2014 at 20:45
  • Please fill CollaborationGroupMember.CollaborationRole column Commented Apr 11, 2018 at 7:51
7

You can also use Chatter in Apex. Here's code you can paste into the Developer Console:

String communityId = null;

List<String> groupMembers = new List<String>{
    '005D0000001Sv24',
    '005D0000001QdEL',
    '005D0000001LLO6'};

public static Id createGroup(String groupName, List<String> users) {

    ConnectApi.ChatterGroupInput groupInput = new ConnectApi.ChatterGroupInput();
    groupInput.name = groupName;
    groupInput.visibility = ConnectApi.GroupVisibilityType.PublicAccess;

    ConnectApi.ChatterGroupDetail g = ConnectApi.ChatterGroups.createGroup(communityId, groupInput);

    for (String user: users) {
        ConnectApi.GroupMember member = ConnectApi.ChatterGroups.addMember(communityId, g.id, user);
    }

    return g.id;

}

createGroup('New Group', groupMembers);

Docs: http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_ConnectAPI_ChatterGroups_static_methods.htm

You must log in to answer this question.

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