This article aims to explain how to display a Salesforce Content Document (ContentVersion) in a custom formula field. Since I discovered the information needed is scattered across the world wide web, summarizing it into 1 blog article seemed to be a great way to enrich the internet!

Here's the scenario.

I want to retrieve an image located somewhere on the internet, save it as a Salesforce File attached to a parent record and display the image on the parent record's detail page.

To achieve this, only a few steps need to be taken. Let's step through them....

1. Create Custom Fields

For demonstrational purposes, let's use Account as the parent entity. It will need 2 new custom fields, one to hold the Content Image Id and one to display the image. For the Id, create a text field, 18 positions long. For this example I will use Image_Id__c.

Secondly, create the formula field that will display the image. The formula should be of type text, and contain the following contents:


IMAGE("/sfc/servlet.shepherd/version/download/"&Image_Id__c, "My Image")

Make sure to add the formula field to the appropriate page layouts.

2. Retrieve and store image

For this, you will need some APEX. Using HTTP callouts, it's possible to fetch a file (e.g. an image) and store it in a File attachment to some Salesforce record. Only 2 records need to be inserted: ContentVersion and ContentDocumentLink.

First, fetch the image and save it as a ContentVersion:


Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://someurl.com/image.png');
req.setMethod('GET');
HttpResponse resp = h.send(req);
Blob imageBody = resp.getBodyAsBlob();
ContentVersion cv =new ContentVersion();
cv.Title = 'Image saved at '+System.Datetime.now();
cv.VersionData= imageBody;
cv.PathOnClient= 'filename.png';
insert cv;

Next, insert the link, ContentDocumentLink, to the parent record:


ContentDocumentLink cl = new ContentDocumentLink();
cl.ShareType = 'V';
cl.Visibility = 'AllUsers';
//
// Needs to be requeried. Bulkify!
cl.ContentDocumentId = [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id = :cv.Id].ContentDocumentId;
cl.LinkedEntityId = <ID of the parent record>;
insert cl;

Finally, store the Id of the document in the parent record, so it can be referenced by the formula field.

Account myAccount; // Some concrete Account object
myAccount.Image_Id__c = cv.Id; // Inserted ContentVersion.Id
update myAccount;

All of the code above should obviously be implemented in some way. If included in a Trigger, make sure to use @future(callout=true) on the image retrieval. Also, the domain called in the HTTPRequest (https://someurl.com) should be added as a Remote Site in the Setup menu.

Test it!

If you execute the code in the appropriate context and return to the parent record, you should now see your image displayed on the page and the file added to the record's attachments.

 

Add comment


Security code
Refresh