Suppose I have a library named xyz and a folder inside it named abc. I am able to insert a file into the library through the apex via the Content Document link. But how to move the file to a folder inside the library? The LinkedEntityId in Content Document link accepts only library id. It does not accept folder id.


ContentDocumentLink cdl = new ContentDocumentLink();
cdl.ContentDocumentId = cv.ContentDocumentId;
cdl.ShareType = 'I';
cdl.Visibility = 'AllUsers';
cdl.LinkedEntityId = ws.Id; //Magic happens here// how to link a folder here?
insert cdl;

2 Answers 2


You need to insert the ContentWorkspaceDoc to associate the document with the library.

List<ContentWorkspaceDoc> workspacedocs = new List<ContentWorkspaceDoc>(); 
ContentWorkspaceDoc wsDoc = new ContentWorkspaceDoc();
wsDoc.ContentDocumentId = contentdoc.id;
wsDoc.ContentWorkspaceId = contentWorkspace.id;
insert workspacedocs;

Where contentWorkspace is the Contentworkspace record and contentdoc is ContentDocument record.

Please note that the folders inside the library are represented as ContentFolder object and the files inside are represented as ContentFolderMember. But as of now Aug 2020, none these objects are creatable using API.


  • I tried this. But am not able to move the file to a sub-folder inside the library.
    – Raji Mohan
    Aug 18, 2020 at 12:03
  • I think that is something you can't do as of now. @RajiMohan Aug 18, 2020 at 12:52
  • Sure, Thank you for your response.
    – Raji Mohan
    Aug 20, 2020 at 6:18

It seems to work if you insert the ContentDocumentLink like you described above, pointing it to the root library (ContentWorkspace):

ContentDocumentLink cdl = new ContentDocumentLink();
cdl.ContentDocumentId = doc.Id;
cdl.ShareType = 'I';
cdl.Visibility = 'AllUsers';
cdl.LinkedEntityId = ws.Id; // library (ContentWorkspace) id
insert cdl;

Then query for the ContentFolderMember record(s) which should be created automatically, and update the ParentContentFolderId field:

ContentFolderMember cfm = [SELECT Id, ChildRecordId, ParentContentFolderId FROM ContentFolderMember WHERE ChildRecordId = :doc.Id LIMIT 1];
cfm.ParentContentFolderId = subfolder.Id; // desired subfolder (ContentFolder) id 
update cfm;

The ContentFolderMember record initially points to the hidden library root ContentFolder and the ChildRecordId field is not writable, but the ParentContentFolderId is.

Couldn't find this documented specifically, but found some other posts that were on the same path:

How to upload a file to content folder using standard file uploader?

How to Upload a File to a specific Library Folder using Apex?

Hope this helps!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .