Site icon WedgeCommerce

How to post to chatter feed from APEX

Most of the Organisation using Salesforce must be knowing about Chatter. For those people who might not be having idea about chatter, in the easiest words we can say that, it is the social network of any Salesforce org. We can post quotes, images, updates, and much more. To enable chatter all we have to do is go to the Setup|Customize|Chatter|Chatter Settings and enable chatter. After that a new chatter tab will be visible in specific apps. However someone might be having a specific requirement about posting data on chatter from APEX code. That is what I’ll be discussing about, how to post to chatter from apex.

Apex Code

public class chatterpost {
public string body { get; set;}
public string userID { get; set;}

public void postFeed(){
FeedItem post = new FeedItem();
post.ParentId = userID;
post.Body = body;
insert post;
}
}

As you can see here we have used an object of the FeedItem class, which is used to post data to chatter. All we have to do is enter the post body and parentId, and then insert the post. You can also provide your own id to the parentId which will result in the post being posted to your own profile.

VisualForce Code

<apex:page controller="chatterpost">
<apex:form>
<table>
<tr>
<td><apex:outputLabel>Enter User ID</apex:outputLabel></td>
<td><apex:inputText value="{!userID}" label="Enter User ID"/></td>
</tr>
<tr>
<td><apex:outputLabel>Enter Post Content</apex:outputLabel></td>
<td><apex:inputTextarea value="{!body}" label="Enter Post Content"/></td>
</tr>
<tr>
<td></td>
<td><apex:commandButton value="Post" action="{!postFeed}"/></td>
</tr>
</table>
</apex:form>
</apex:page>

In the Visualforce Code we have just got the data that we want to create a post on chatter. Once after entering the data, click on the post button and then quickly move to the chatter tab to see the updates.

Output

The output of my code will be as follows:

Support

That’s all about creating a post on chatter through APEX, for any further queries feel free to contact us at:

https://wedgecommerce.com/contact-us/

Or let us know your views on how to make this code better, in comments section below.

Exit mobile version