1

I am trying to create new File through ContentVersion and Associating it with Custom Object ParentId is ID of Custom Object .

Error given is Document: You cannot create a link for a document in a private library.

EXCEPTION_THROWN [356]|System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, You cannot create a link for a document in a private library: [ContentDocumentId]

Following is my Code ,

        public ID createFileFromUploadedFile(Id parentId) {
        ID docID = null;
        ContentVersion cv = new ContentVersion();
        cv.versionData =  file.Body;
        cv.title = file.FileName;
        cv.pathOnClient = file.FileName;
    insert cv;

    docID = cv.id;
        ContentVersion currentDoc = [SELECT ContentDocumentId from 
                                     ContentVersion  where id =:docID];
        docID = currentDoc.ContentDocumentId;
        ContentDocumentLink cdl = new ContentDocumentLink();
        cdl.ContentDocumentId = currentDoc.ContentDocumentId;
        cdl.LinkedEntityId = parentId;
        cdl.ShareType = 'S';
        insert cdl;

    return docID;
}
2

You should add location for the file (the library), I use ContentLocation for creating my ContentVersion:

    ContentVersion cv = new ContentVersion();
    cv.ContentLocation = 'S'; // S = within Salesforce, E = External
    cv.VersionData = body;
    cv.Title = fileName;
    cv.PathOnClient = filename;

    insert cv;
2

I ran across this the other day while converting a process that was using attachments to use the new Files feature. What fixed it for me was setting the FirstPublishedLocationId to the record.

So in your example

public ID createFileFromUploadedFile(Id parentId) {
        ID docID = null;
        ContentVersion cv = new ContentVersion();
        cv.versionData =  file.Body;
        cv.title = file.FileName;
        cv.pathOnClient = file.FileName;
     ** cv.FirstPublishLocationId = parentId **
    insert cv;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.