Wednesday, February 12, 2020

How to get related files of the record using apex in salesforce

Use the below sample code to get the files related to the record using apex.
This code works for bulk records pass the list of parent ids to the method, based on parent ids it returns the files associated with the parent record.

Apex Code
public inherited sharing class ContentUtility {
 public static map<Id, list<ContentVersion>> getRelatedFiles(list<Id> lstParentIds) {

        map<Id, list<ContentVersion>> mapParentIdAndFiles = new map<Id, list<ContentVersion>>();
        map<Id, Id> mapCntIdParentId = new map<Id, Id>();

        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>());
        return mapParentIdAndFiles;

Sample Code
System.debug('Related Files ===>'+ContentUtility.getRelatedFiles(new list<Id>{'a1Z54000001NplZ'}));

No comments:

Post a Comment