Saturday, April 17, 2021

Upload Content Document with custom field populated from a Visualforce page

In a previous post, we looked at how to upload files as attachment without exceeding heap size governor limit. Link to post: https://blog.moothien.me/2017/05/upload-attachment-to-salesforce-without.html

However, most implementation nowadays make use of Content Document to store files since the Spring '16 rollout. 

Here I will show you how to upload file to Salesforce as Content Document attached to a record. At the same time, you will also be able to populate fields (standard and custom) on the Content Version record. 

First of all, let's take a look at the data model for Content Document. 


As you can see in the ERD above, the process of creating a Content Document is a bit different. The object Content Document cannot be created on its own, a Content Version needs to be uploaded first. This process will automatically create the Content Document. Now, to link the Content Document to the your record, a Content Document Link needs to be created which will store the relationship between your record and the uploaded file. 

This requires at least three APIs call to Upload: 

  1. upload a file will create a Content Version and will return the Id of the Content Version
  2. Use this Id to get the Content Document Id which has been auto created
  3. Use the Content Document Id and create a Content Document Link which relates to your record
Luckily for us, Salesforce has a special type of API request named Composite Resources which can execute Dependent Requests in a Single API Call. (Read more about Composite Resources here: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/using_composite_resources.htm)

Here is how the composite resource body is built and where to populate the custom field.


In the payload, you will notice a key referenceId. It will create a variable with this name and will be populated with the response of the current request, which can then be used to sub request.


Composite resource makes use of the following endpoint '/services/data/v51.0/composite'. A session Id is also required to authenticate the request. 

Here is the full code:



Demo

Upload a file with custom attributes


The result on Salesforce


Resources:


1 comment:

  1. New casino platforms are coming out every month, and roulette 온라인카지노 fans are spoilt for choice. Now have the ability to|you probably can} play European, American, and all different forms of roulette despite your geographical location. Also, there are considerable advantages to playing in} the sport on-line, rather at a brick-and-mortar casino.

    ReplyDelete