Posting to Chatter with Apex Code

Haven't wrote here for some time...Hope you can find the post interesting.

I discover  recently the option to post into chatter with apex code. Some might think it's complicated or aren't familiar with it at all so they aren't using it, however after getting familiar you will see it's quite easy and can be very useful.

I wrote 2 generic functions that post to chatter. Find them useful for several cases.
First method using the ConnectAPI, second without, and I'll explain later the reason for needed
both.

1.ConnectAPI
The ConnectAPI provide some build-in functions and objects to post in chatter.
You can read the SF Documentation regarding, but wait! You can easily get lost in too much information and too many examples, which mostly are not relevant. Advise, is to start with the code below.
Later search specifically classes according to your needs (can google it by 'salesforce + <API Object name>').


public static void CreatePostAttach(  
  Id recordID,   
  string s_FileURL,   
  string s_fileType,   
  string s_fileName,   
  string s_msg,   
  list<string> ls_mentionUser)  {  

 ConnectApi.FeedItemInput input = new ConnectApi.FeedItemInput();  
 ConnectApi.BinaryInput feedBinary;  
 ConnectApi.MessageBodyInput messageInput = new ConnectApi.MessageBodyInput();  
 messageInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();  
 ConnectApi.TextSegmentInput textSegment = new ConnectApi.TextSegmentInput();  
 textSegment.text = s_msg;  
 messageInput.messageSegments.add(textSegment);   

 for(string userId : ls_mentionUser){  
  ConnectApi.MentionSegmentInput mentionSegment = new ConnectApi.MentionSegmentInput();  
  mentionSegment.id = userId;  
  messageInput.messageSegments.add(mentionSegment);  
 }  
 input.body = messageInput;  
 
 if(s_fileName!=null){  
  PageReference p = new PageReference(s_FileUrl);  
  p.setRedirect(true);  
  blob body=p.getContent();  
  ConnectApi.NewFileAttachmentInput fileIn = new ConnectApi.NewFileAttachmentInput();  
  fileIn.title = s_fileName + '.' + s_fileType;  
  input.attachment = fileIn;  
  feedBinary = new ConnectApi.BinaryInput(body, s_fileType, s_fileName + '.' + s_fileType);  
 }  
 ConnectApi.FeedItem feedItemRep = ConnectApi.ChatterFeeds.postFeedItem(null, ConnectApi.FeedType.Record, recordID, input, s_fileName!=null ? feedBinary : null);  
}  


This method get 6 parameters:
1.The record Id, to post under its chatter.
2.Attachment URL (optional) - in case you want to add attachment with the post.
3.Attachment Type - in case you provide the Attachment URL, you should provide also the file type.
4.Attachment Name
5.Text Message - The content of the post.
6.list of users to Mention - who should be mentioned at the end of the message.

Assume the rest of the code it's quite self explain. The main object is the FeedItemInput, we add to it MessageBodyInput for the text, MentionSegmentInput for users mentioning.
In addition using the BinaryInput for the attachment.

Example (Result shown in the image at the bottom):
CreatePostAttach(
        '001w0000019yccM',
        '/apex/AccountPage?id=001w0000019yccM',
        'pdf',
        'AccountRep.pdf',
        'Hi..I added this Pdf report.\n\n Visit:\n http://lc169.blogspot.co.il/\n\n',
        new list<string>{'005w0000003Yf6L', '005w0000003Z6Zm'});

-Note: AccountPage is simple visual page render as Pdf that I created.


2.Insert FeedItem
We can do almost the same action without the ConnectAPI- but create and insert new FeedItem.
Which is the second method.
Why I needed it? When using ConnectAPI the submitter of the post is always the current user.
Let's assume you want to post it with admin user, perhaps when critical error occur then it cannot be done with ConnectAPI. You can do it by creating the FeedItem yourself.
The drawback with this method is that you cannot use the mention part.


public static void CreatePostAttachUser(  
  Id recordID,      //Related record ID  
  string s_FileUrl,    //URL to generate attachment  
  string s_postType,     
  string s_fileName,   //File Name  
  string s_msg,      //Message content  
  string createUser){   //User that create. If null then it'll current user     
 
 FeedItem post = new FeedItem();  
 post.ParentId = recordID;  
 post.createdById = createUser;  
 post.Body = s_msg;  
 post.type = s_postType;  
 
 if(s_fileName != null){  
  PageReference p = new PageReference(s_FileUrl);  
  p.setRedirect(true);  
  blob body=p.getContent();  
  post.ContentData = body;  
  post.ContentFileName = s_fileName;     
 }  
 insert post;  
}  

This method also get 6 parameters:
1.Record ID to post under.
2.Attachment URL (optional)
3.Post type - should match one of the picklist value from the Feed Types. In case it post with attachment value should be- 'ContentPost'
4.Attachment Name
5.Text Message
6.User Id of the submitter

Example:
CreatePostAttachUser(
        '001w0000019yccM',
        '/apex/AccountPage?id=001w0000019yccM',
        'ContentPost',
        'AccountRep.pdf',
        'Hi..I added this Pdf report.\n\n Visit:\n http://lc169.blogspot.co.il/\n\n',
        '005w0000003Z6Zm');







Retire of Permission on Profiles

If you are working as a Salesforce admin/developer you've probably heard somewhere that Salesforce is planning to make a significant cha...