I am working on replacing my attachments with Files. I have created an apex class to create the ContentVersion record but I have been unable to create the ContentDocumentLink object to link the document to my case. The below code creates the file, I just need some help on how I link this to the case. How do I query for the ContentVersion of the newly created record and apply that to the ContentObjectLink?

 public PageReference SaveandClose() {
    system.debug('Here is the Description ' + cv.Description);
    //Get the ContentVersion RecordTypeID for ABM Case
    string CVRTID = [select id, name from recordtype where sObjectType = 'ContentVersion' and Name = 'ABM Case'].Id;

    ContentVersion v = new ContentVersion();
    v.RecordTypeId = CVRTID;
    v.versionData = file;
    v.title = cv.title;
   v.Description = cv.Description;

    v.Document_Type__c = cv.Document_Type__c;
    v.pathOnClient ='/somepath.txt';
    insert v;
    //return new PageReference('/' + v.id);
    return null;


1 Answer 1


The ContentDocument can be queried from the ContentVersion.

v = [SELECT ContentDocumentId FROM ContentVersion WHERE Id = :v.Id];
ContentDocumentLink cdl = 
  new ContentDocumentLink(
    LinkedEntityId=caseRecord.Id, ...);
insert cdl;
  • Thanks so much!!! I appreciate your help!
    – Frank
    Feb 23, 2019 at 0:54

You must log in to answer this question.

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