Chatter Comments

The handling of Chatter comments is slightly different from that of other Chatter data. Comment data is stored in a single, large object called FeedComment that cannot be queried directly. The Feed object becomes a junction object, associating Chatter posts to the subject of the post and zero or more comments. This three-way relationship is shown in Figure 12.2, with the left side the parent of the post and the right side the list of comments.

Image

Figure 12.2 Chatter comment schema pattern

The relationship between the Feed junction object and the FeedComment object is called FeedComments. Listing 12.6 provides an example of querying it. The result is all the posts in the Project__c custom object feed and all of the comments for each post.

Listing 12.6 Chatter Query for Comments


SELECT ParentId, Type, CreatedById, CreatedDate, Body,
  (SELECT CommentBody, CreatedById, CreatedDate FROM FeedComments)
  FROM Project__Feed


To create a comment, insert a record into the FeedComment object. Listing 12.7 provides a sample method for doing this. To test it, you need the Id value of a record in a Feed object. For example, if you want to add a comment to an Account post, get the Id of the post to comment on from the AccountFeed object. This Id value is then passed into the method as the first argument, postId. The second argument is the text of the comment to create. Save the postId and the value returned by this method, as these are needed to delete the comment.

Listing 12.7 Creating a Chatter Comment


public Id comment(Id postId, String text) {
  FeedComment comment = new FeedComment(
    FeedItemId = postId, CommentBody = text);
  insert comment;
  return comment.Id;
}


You cannot update a FeedComment record, but you can delete it. Like with deleting posts, deleting comments is tricky because you cannot directly query the FeedComment object to retrieve the record to delete. If your program creates or queries FeedComment records and can keep them around in a cache, that is ideal. If this is not possible, you must query the FeedComment object in order to delete it.

Listing 12.8 shows a sample method for deleting a comment by querying it first via its parent post. To use it, you must pass the FeedItemId of the parent post in the Project__Feed object as the postId, and the Id of the FeedComment record as commentId, returned by the comment sample method. Although this example operates on comments in Project__Feed only, the same pattern can be applied to comments in all feeds.

Listing 12.8 Deleting a Chatter Comment


public void deleteComment(Id postId, Id commentId) {
  Project__Feed post = [ SELECT Id,
    (SELECT Id from FeedComments WHERE Id = :commentId)
    FROM Project__Feed WHERE Id = :postId ];
  delete post.FeedComments[0];
}


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.13.76