I'm getting insufficient privileges error when I try to create a new version for an existing file in apex.

Code used to create new version:

        ContentDocumentLink cdl = [SELECT ContentDocumentId FROM    ContentDocumentLink WHERE LinkedEntityId = :parentId LIMIT 1];

        ContentVersion contentVersion = new ContentVersion(
            ContentDocumentId = cdl.ContentDocumentId,
            Title = attachmentName,
            PathOnClient = attachmentName,
            ReasonForChange = 'Document replaced by user',
            VersionData = EncodingUtil.Base64Decode(attachmentBody),
            IsMajorVersion = true

        insert contentVersion;

Error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []


This error occurs because the user does not have permission to see the ContentDocument to which you're trying to attach the file. I suspect the reason for this is that you have WHERE LinkedEntityId = :parentId LIMIT 1 in your query. If the object (Account, Contact, what have you) identified by parentId has more than one file attached to it, that query is going to get you the Id of just one of them, and it may not be the ContentDocument you actually intend to be working with.

It's not clear whether or not you're running this code and the code to create the first ContentVersion in the same user context, but that's worth confirming. Additionally, even if you find that this works or doesn't work once, it's not going to work in production with that LIMIT clause in there.

Before focusing on potential code issues, you should also make sure the running user can upload new versions completely through the UI.

  • David thanks for your response. I checked if the ContentDocumentId returned by the SOQL points to the right file in system debug and it seems OK. However I noticed the file is missing the 'Upload New Version' link on the detail page that normally appears when I create it using the UI. I created this file using apex below: ContentVersion contentVersion = new ContentVersion( Title = attachmentName, PathOnClient = attachmentName, VersionData = EncodingUtil.Base64Decode(attachmentBody), IsMajorVersion = true );
    – Swatz
    Feb 23 '18 at 11:14

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.