2

I want to post a message to a specific Chatter group using Apex.

If I understand it correctly, Chatter groups are stored in the CollaborationGroup object.

Therefore, I want to do something like:

public static void postToChatter(String chatterGroupId) {
    if(chatterGroupId instanceof Id) {
        CollaborationGroup chatterGroup = [select Id, Name from CollaborationGroup where id = :chatterGroupId];
        FeedItem post = new FeedItem();
        post.Title = 'My Title';
        post.Body = 'My message body';
        post.ParentId = chatterGroup.Id;
        insert post;
    }
} 

I see that the parent could be any ActorWithId class. One of its subclasses is ChatterGroup, but this class is abstract. It doesn't seem it makes sense (or is possible) to instantiate its implementations.

  • 1
    Are you getting an error when you use this? I have code very similar to this in production in several orgs. – JimRae Feb 7 '14 at 22:19
  • Actually, I was thinking I had to instantiate a Chatter group and pass it to post.Parent. Then I realized the Id might be enough (and updated the question). I still have to test it, but thanks for letting me know you have some like this working. – ceiroa Feb 7 '14 at 22:23
3

You can also use the ConnectAPI:

ConnectApi.FeedItem fi = ConnectAPI.ChatterFeeds.postFeedItem(null, ConnectApi.FeedType.Record, '0F9L00000004ahL', 'My Test Post');
  • Two questions: 1. What is the advantage of doing it this way 2. where are you telling it which chatter group to post to – ceiroa Feb 8 '14 at 0:01
  • 1
    This is the Chatter Group Id: '0F9L00000004ahL' (see the docs for more explanation of each param) For a simple post, there is no real benefit - where it becomes more important is when you want to do more complex posts e.g. include @mentions, rich text etc. At that point, you have to use ConnectAPI - so for consistency, I tend to use ConnectAPI even for simple posts, so I am not switching between styles. They just released a new helper class to make messageSegments (the core framework for complex posts) easier to use - you can see more explanation here (goo.gl/xKgNlK) – BritishBoyinDC Feb 8 '14 at 0:40
  • After trying this code I got this error: "Method was removed after version 31.0: postFeedItem".. – Yonatan Goriachnick May 28 '17 at 12:25
  • So for orgs with a higher API version the 'insert' approach is better.. See here for example. – Yonatan Goriachnick May 28 '17 at 13:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.