Wednesday, February 5, 2020

How to delete files from Content Workspace library using Apex in salesforce

Assume you have a Content Workspace library is 'Test Library' and you have few files in that library.
Now your requirement is to delete all the files from library using apex.

Test Library


Apex Code
Id idLinkedEntity = [SELECT Id FROM ContentWorkspace WHERE Name = 'Test Library' LIMIT 1].Id;

list<ContentDocument> lstCntDocsToDelete = new list<ContentDocument>();

for(ContentDocumentLink iterator : [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId =:idLinkedEntity]) {
    lstCntDocsToDelete.add(new ContentDocument(Id = iterator.ContentDocumentId));
}

if(!lstCntDocsToDelete.isEmpty() && lstCntDocsToDelete != null) {
    Database.delete(lstCntDocsToDelete, false);
    Database.emptyRecycleBin(lstCntDocsToDelete);
}

above code deletes all files from the content workspace library.



Resource
ContentWorkspace

1 comment:

  1. How to delete all folders of the library, too?

    ReplyDelete