February 22, 2016

How to get @mentioned user from Feed Item in Salesforce?

Sample Code:

String communityId = null;
String feedItemId = '0D529000001ABmQCAW';//Sample FeedItem Id

ConnectApi.FeedElement feedItem = ConnectApi.ChatterFeeds.getFeedElement(communityId, feedItemId);
List<ConnectApi.MessageSegment> messageSegments = feedItem.body.messageSegments;
for (ConnectApi.MessageSegment messageSegment : messageSegments) {
    if (messageSegment instanceof ConnectApi.MentionSegment) {
        ConnectApi.MentionSegment mentionSegment = (ConnectApi.MentionSegment) messageSegment;
        System.debug('Mentioned user name: ' + mentionSegment.name);
        System.debug('Mentioned user id: ' + mentionSegment.record);
    }
}

2 comments:

  1. The if part is not working as the messageSegment is not the instance of mention segment

    ReplyDelete
    Replies
    1. Check the Feed Item Id to debug the issue. Make sure the feed has user mentioned.

      Delete