+ Start a Discussion
s_macs_mac 

post to chatter group using apex

Hi ,

 

I have  to write an apex trigger,on my custom object,after creating a record,following are the requirements

chatter group should be created and users should be added,

description field of my custom object should be posted on chatter.

 

Pawan Kumar 32Pawan Kumar 32
trigger CreateOfferChatter on customobject__c (after Insert) {

  Set<Id> offerIds = new Set<Id>();  
  
  for(customobject__c offer : Trigger.new){
  
      offerIds.add(offer.id);
  }
  
  Map<Id, customobject__c> map_offer =  new Map<Id, customobject__c>([select id, name, LS_Project__r.Name from offer__c where id IN: offerIds]);

  for(customobject__c offer : Trigger.new){
  
    system.debug('@@Trigger Map : ' + map_offer );
    system.debug('@@Trigger Map values : ' + map_offer.values() );
    
    customobject__c offermap = map_offer.get(offer.id);
    system.debug('@@TRigger offermap  : ' + offermap );
    String feedMessage = ' New offer has been created for LS project : ' + offermap.LS_Project__r.Name;
    ConnectApi.MessageBodyInput messageInput = new ConnectApi.MessageBodyInput();
        messageInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();
        ConnectApi.FeedItemInput inputdata = new ConnectApi.FeedItemInput();
        ConnectApi.TextSegmentInput textSegment = new ConnectApi.TextSegmentInput();
        String finalTextSeg = feedMessage;
            //Adding (@mention) in chatter
            
         String userToMention = UserInfo.GetUSerId();
         ConnectApi.MentionSegmentInput mentionSegment = new ConnectApi.MentionSegmentInput();
         mentionSegment.id = userToMention;
         messageInput.messageSegments.add(mentionSegment);
        ////Adding feed message in chatter
        textSegment.text = finalTextSeg;
        messageInput.messageSegments.add(textSegment);        
        inputdata.body = messageInput;
        inputdata.feedElementType = ConnectApi.FeedElementType.FeedItem;
        inputdata.subjectId = (String) offer.id;        
        try{
         
          ConnectApi.FeedElement feedElement = ConnectApi.ChatterFeeds.postFeedElement(null, inputdata);

        }
        catch(Exception e){
          System.debug('Exception : ' + e);
        } 
  }


}
Please refer the above code. It might help. If you feel this code helps you, Please mark as best answer.

Good LucK!!
Pawan