function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jonathan Wolff 7Jonathan Wolff 7 

Populate Version Id through trigger

Hello, I have a trigger that populates the ContentDocumentId into a field. Now i would to like to populate the version Id too, but i dont know how to get it into the field VersionId__c  
trigger ContentIdEintragen on ContentDocumentLink (after insert, before update) {
    
    map<id,id> parentids = new map<id,id>();
    
    for(ContentDocumentLink cdl:trigger.new){
        parentids.put(cdl.LinkedEntityId,cdl.ContentDocumentId);
    }
    
    List<Mediathek__c> ContentDocumentIdupdate = new List<Mediathek__c>();
    
    for(Mediathek__c mt:[select id from Mediathek__c where id IN:parentids.keyset()]){
        
        if(parentids.containskey(mt.id)){
            mt.ContentDocumentID__c = parentids.get(mt.id);
            mt.VersionId__c =... ;
            ContentDocumentIdupdate.add(mt);
        }
    }
    update ContentDocumentIdupdate;
}

 
Syed Insha Jawaid 2Syed Insha Jawaid 2
Hi Jonathan

You can use Contentdocument record to fetch the latest version id.

LatestPublishedVersionId – This is a lookup field that stores the ID of the current ContentVersion of the document.

//Code snip
Set < Id > setOfContentDocIds = new Set < Id >();
for(ContentDocumentLink cdl:trigger.new){
parentids.put(cdl.LinkedEntityId,cdl.ContentDocumentId);
setOfContentDocIds.add(cdl.ContentDocumentId)
}

Map < Id, ContentDocument > mapOfContentDocument = new Map < Id, ContentDocument >([SELECT Id, LatestPublishedVersionId FROM ContentDocument WHERE Id IN : setOfContentDocIds]);

for(Mediathek__c mt:[select id from Mediathek__c where id IN:parentids.keyset()]){
if(parentids.containskey(mt.id)){

mt.ContentDocumentID__c = parentids.get(mt.id);
mt.VersionId__c = mapOfContentDocument.get(parentids.get(mt.id)).LatestPublishedVersionId;
ContentDocumentIdupdate.add(mt);
} }