I am inserting ContentVersion as following:-

String yourFiles = 'Lets assume this is your binary string of the files';
ContentVersion conVer = new ContentVersion();
conVer.ContentLocation = 'S'; // S specify this document is in SF, use E for external files
conVer.PathOnClient = 'ionicLogo.png'; // The files name, extension is very important here which will help the file in preview.
conVer.Title = 'Proposal '; // Display name of the files
conVer.VersionData = EncodingUtil.base64Decode(yourFiles); // converting your binary string to Blog
insert conVer;

Then i used system debug to get ContentDocumentId as following:-

system.debug( 'id'+conVer.ContentDocumentId);

But when i check the debug log i got null value.

After that, I run a soql query on ContentVersion as following:-

ContentVersion cv=[select id, ContentDocumentId from ContentVersion where id=:conVer.id];

Here I got the ContentDocumentid for the above inserted ContentVersion.

But i know once you insert contentversion through anonymous window in developer console,one contentDocumentlink with linkentityid equals to user id and one contentDocument is also inserted.

ContentDocumentLink cdl=[select id from ContentDocumentLink where ContentDocumentId =:cv.ContentDocumentId];
contentDocument cd=[select id from contentDocument where id=:cv.ContentDocumentId];

I am getting the values in debug log for both the debugs.

My question is why i am not able to directly fetch the contentdocumentid just after insertion of contentVersion record but can fetch by doing a soql query on same contentVersion???

1 Answer 1


The only value that gets updated in the Apex instance for any SObject when you insert is the Id value. Other fields populated as part of the insert by triggers or other logic have to be re-queried to get the values - ContentVersion is no different.

Quite a lot can go on behind the scenes for ContentVersion, including the automatic addition of a ContentDocumentLink to the User who inserted the version.

I've found ContentNote/ContentDocument/ContentVersion/ContentDocumentLink quite awkward to work with compared to e.g. just a Note.

  • Thanks for your response. As you said, I have tried debugging other fields too just after insertion, i can able to fetch those value in debug logs. Only exception is ContentDocumentID. Aug 19, 2018 at 9:14
  • Fabulous answer. was struggling with this for quite some time.
    – Saariko
    Dec 13, 2021 at 22:28

You must log in to answer this question.

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