Hello everyone, today we’re going to discuss Retrieving Related Files for a Record in Apex: Best Practices. In Salesforce, handling files and attachments related to records is a common requirement. This blog will guide you through the process of fetching related files of a record using Apex. We’ll explore the key objects involved, the Apex code needed, and some best practices to keep in mind.
Salesforce introduced the ContentDocument
and ContentDocumentLink
objects to handle files.
Also, check this: Email Quick Action in LWC
Key Highlights :
- ContentDocument: Represents a document that has been uploaded to a library in Salesforce CRM Content or Salesforce Files.
- ContentDocumentLink: Represents the link between a Salesforce CRM Content document or Salesforce file and where it’s shared.
Code :
To fetch files related to a specific record, we will leverage these objects. Here’s a step-by-step guide:
- Identify the Record ID: You need the ID of the record for which you want to fetch related files.
- Query ContentDocumentLink: Fetch
ContentDocumentLink
records where theLinkedEntityId
matches your record ID. - Retrieve ContentDocument Details: For each
ContentDocumentLink
, fetch the correspondingContentDocument
to get file details.
FileService.cls:
public with sharing class FileService { /** * Fetches related files of a given records. * * @param listParentIds The IDs of the records whose related files are to be fetched. * @return Map<Id, list<ContentVersion>> representing the related files. */ public static Map<Id, list<ContentVersion>> fetchRelatedFiles(list<Id> listParentIds) { Map<Id, list<ContentVersion>> mapParentIdAndFiles = new Map<Id, list<ContentVersion>>(); Map<Id, Id> mapCntIdParentId = new map<Id, Id>(); // Query ContentDocumentLink to get the IDs of related ContentDocuments for(ContentDocumentLink cntLink : [Select Id, ContentDocumentId, LinkedEntityId From ContentDocumentLink Where LinkedEntityId IN :lstParentIds]) { mapCntIdParentId.put(cntLink.ContentDocumentId, cntLink.LinkedEntityId); } if(!mapCntIdParentId.isEmpty()) { for(ContentVersion cv : [SELECT Id, Title, VersionData, ContentDocumentId FROM ContentVersion WHERE ContentDocumentId IN :mapCntIdParentId.keySet() AND IsLatest = True]) { if(!mapParentIdAndFiles.containsKey(mapCntIdParentId.get(cv.ContentDocumentId))) { mapParentIdAndFiles.put(mapCntIdParentId.get(cv.ContentDocumentId), new list<ContentVersion>()); } mapParentIdAndFiles.get(mapCntIdParentId.get(cv.ContentDocumentId)).add(cv); } } return mapParentIdAndFiles; } }