Upload a File to a specific Library Folder using Salesforce Apex

Upload a File to a specific Library Folder using Salesforce Apex

ContentDocumentLink record should be created with LinkedEntityId as the Library Id to upload a File to a specific Library Folder using Salesforce Apex.

In the following example, when Files are uploaded to Case records, it will link them to a Library with the name ‘Public Library”.

Sample Apex Trigger:

trigger ContentDocumentLinkTrigger on ContentDocumentLink (
    after insert
) {
    
    ContentWorkspace objWorkspace = [
        SELECT Id 
        FROM ContentWorkspace 
        WHERE Name = 'Public Library' 
        LIMIT 1
    ];
    List < ContentDocumentLink > listCDLs = 
        new List < ContentDocumentLink >();
    
    for ( ContentDocumentLink objCDL : trigger.new ) {
       
        String strEntityId = objCDL.LinkedEntityId;
        
        if ( 
            String.isNotBlank( objCDL.LinkedEntityId ) && 
            strEntityId.left( 3 ) == '500' 
        ) {
       
            ContentDocumentLink objCDLNew = new ContentDocumentLink();
            objCDLNew.ContentDocumentId = objCDL.ContentDocumentId;
            objCDLNew.ShareType = 'I';
            objCDLNew.Visibility = 'AllUsers';
            objCDLNew.LinkedEntityId = objWorkspace.Id;
            listCDLs.add( objCDLNew );
           
        }
        
    }
    
    if ( listCDLs.size() > 0 ) {
        
        insert listCDLs;
        
    }

}

Leave a Reply