[SalesForce] Show Chatter image in Formula field

So we have an object to which some images are attached via the Chatter feed.

Imagine the Id of the FeedItem is 0D5b000000L3ZEE.

Now I want to have a formula field that uses the IMAGE() function to display that attached image. How would I do that?

I imagine using an Apex trigger that creates the URL at which the image can be viewed. And then formula field looks up that URL and displays the image. But what is the correct URL that I can use?

Best Answer

The FeedItem has a field called RelatedRecordId which is defined as:

ID of the ContentVersion object associated with a ContentPost. This field is null for all posts except ContentPost. For example, set this field to an existing ContentVersion and post it to a feed as a FeedItem object of TypeContentPost.

If you right click on the download link for the chatter image you get an URL for the download.

It will be something like: https://c.na15.content.force.com/sfc/servlet.shepherd/version/download/068i0000002EqDEBQ5?asPdf=false&operationContext=CHATTER

The ID portion of the URL, 068i0000002EqDEBQ5, is the ContentVersion ID, which is the same as the RelatedRecordId on the FeedItem.

Putting it all together...

Create a custom text field on your object called Content_Version_ID__c and capture the FeedItem’s RelatedRecordId in it (code below). Construct an IMAGE formula field with the following formula:

IMAGE("/sfc/servlet.shepherd/version/download/“ & Content_Version_ID__C, "Chatter Image")

Here is the FeedItem trigger code to copy the RelatedRecordId to the custom Content_Version_ID__c field. I wrote it to work for Leads, but you can modify it for whatever Object you need.

trigger FeedItemTrigger on FeedItem (after insert) {
    Map<Id, Id> possibleRelateds = new Map<Id, Id>();
    for (FeedItem fi : Trigger.New) {
        if (fi.RelatedRecordId != null) {
            possibleRelateds.put(fi.RelatedRecordId, fi.ParentId);  
        }
    }

    Map<Id, Lead> leads = new Map<Id, Lead>();
    for (FeedItem fi : [
         Select Id, RelatedRecordId, ParentId
         From FeedItem
         Where Parent.Type = 'Lead' 
               And ParentId In :possibleRelateds.values()
    ]) {
        if (fi.RelatedRecordId != null &&
            possibleRelateds.get(fi.RelatedRecordId) == fi.ParentId &&
            !leads.keySet().contains(fi.ParentId)
        ) {
            Lead leadToUpdate = new Lead( 
                Id = fi.ParentId, 
                Content_Version_ID__c = fi.RelatedRecordId
            );
            leads.put(leadToUpdate.Id, leadToUpdate);
        }
    }
    update leads.values();
}

As noted, this will not update to point to a newer version of the file if a newer version is uploaded.

Related Topic