function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
RavishankarRavishankar 

Create chatter group using apex

 How can I create group using apex by programming.

i want to create group whan  a (after insert)trigger fire than a group create.

please tell me what code is use for creating group for chatter in apex.

 

 

Pradeep_NavatarPradeep_Navatar

Find below a sample trigger code for creating a group. You can try this out for chatter group :

 

trigger sec_CreateGrp on User (after insert)
{
   try {            
    ID GrpId;
    String strGrpName;
    Integer sz = Trigger.new.size();
    for(integer i=0; i< sz;  i++ )
    {
    User usr = Trigger.new[i];
    Id prflId = usr.ProfileId;
    Id conId = usr.ContactId;
    Profile[] prfNm = [select Name from Profile where Id =: prflId];
    //system.debug('XXX   KKK   ' + prfNm[0].Name );
    if(prfNm[0].Name == 'Partner Staff')
    {
    Contact[] con = [select AccountId from contact where Id =: conId];
    strGrpName = 'Z_' + con[0].AccountId;
        CollaborationGroup[] grpRec = [Select g.Name From CollaborationGroup g where g.Name =: strGrpName limit 1];
    if(grpRec.size() == 0)
    {
    CollaborationGroup grp= new CollaborationGroup();
    grp.Name = strGrpName;                    
    insert grp;
    GrpId = grp.Id;
    }
    else
    {
    GrpId = grpRec[0].Id;                   
    }
    CollaborationGroupMember grpMr = new CollaborationGroupMember();
    grpMr.memberid = usr.Id;
    grpMr.CollaborationGroupId = GrpId;
    insert grpMr;  
    }
                           
}            
                    
}
  catch (Exception e)
  {
   // Generic exception handling code here Contact.AccountId
   system.debug('Exeption ->  ' + e );
  }
}

 

Hope this helps.