[SalesForce] associate File With Custom Object but getting Error

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;
}

Best Answer

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;
Related Topic