[SalesForce] How to use ConnectApi.LinkCapabilityInput to create Chatter posts from Apex

I need to use Apex to create a chatter post on an Account object, which will include some text which is a clickable hyperlink. After hours of confusing searches, I thought I had found the solution here, which looks like it does what I need using LinkAttachmentInput but when I tried it out I discovered:

ConnectApi.LinkAttachmentInput
This class isn’t available in version 32.0 and later. In version 32.0 and later, use the ConnectApi.LinkCapabilityInput class.

Unfortunately, after more hours of searching online, I can't find any examples of how to use this new "capabilities" scheme. Has anyone managed to figure out how to use it to embed a link in a post to be created by calling ConnectApi.ChatterFeeds.postFeedElement() ?

Best Answer

Here's some sample code, which I adapted from an example for posting files:

// Define the FeedItemInput object to pass to postFeedElement
ConnectApi.FeedItemInput feedItemInput = new ConnectApi.FeedItemInput();
feedItemInput.subjectId = 'me';

ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();
textSegmentInput.text = 'Check out this link.';

// The MessageBodyInput object holds the text in the post
ConnectApi.MessageBodyInput messageBodyInput = new ConnectApi.MessageBodyInput();
messageBodyInput.messageSegments = new List<ConnectApi.MessageSegmentInput>();
messageBodyInput.messageSegments.add(textSegmentInput);
feedItemInput.body = messageBodyInput;

// The FeedElementCapabilitiesInput object holds the capabilities of the feed item.
// For this feed item, we define a link capability.

ConnectApi.LinkCapabilityInput linkInput = new ConnectApi.LinkCapabilityInput();
linkInput.url = 'https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_connectapi_input_link_capability.htm';
linkInput.urlName = 'Doc link';

ConnectApi.FeedElementCapabilitiesInput feedElementCapabilitiesInput = new ConnectApi.FeedElementCapabilitiesInput();
feedElementCapabilitiesInput.link = linkInput;

feedItemInput.capabilities = feedElementCapabilitiesInput;

// Post the feed item. 
ConnectApi.FeedElement feedElement = ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), feedItemInput);
Related Topic