Reading list Switch to dark mode

    How to post to chatter feed from APEX

    Updated 16 July 2021

    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:

    image

    Support

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

    Searching for an experienced
    Salesforce Company ?
    Find out More

    https://webkul.uvdesk.com/en/customer/create-ticket/

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

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home

    Table of Content