4

I have a simple trigger designed to prevent updating the metadata for an existing ContentDocument but it's not working. Example code:

trigger ContentDocument_PreventUpdate on ContentDocument (before update) {

    for ( ContentDocument oldCd : Trigger.old ){

        ContentDocument newCd = Trigger.newMap.get(oldCd.Id);
        System.debug('oldCd.Title: ' + oldCd.Title);
        System.debug('oldCd.Description: ' + oldCd.Description);
        System.debug('newCd.Title: ' + newCd.Title);
        System.debug('newCd.Description: ' + newCd.Description);

        if ( oldCd.Title != newCd.Title || oldCd.Description != newCd.Description ){
            oldCd.addError('You do not have permission to edit this record.');    
        }
    }
}

If I update a ContentDocument's title and description, the values are showing in the debug logs as identical between Trigger.old (oldCd variable) and Trigger.new (newCd variable). Am I missing something obvious here?

  • It seems very suspicious to me that this question already has two up votes. – Martin Lezer Jan 8 at 16:29
  • 1
    I think changes are recorded in ContentVersion object, not ContentDocument. Example: help.salesforce.com/articleView?id=000206398&type=1 – David Cheng Jan 8 at 16:29
  • @DavidCheng Using the same approach on a ContentVersion works, assuming I apply the addError statement to the sObject in Trigger.new. Seems unintuitive that these fields would be tied to specific version rather than the ContentDocument itself, but as long as it works I'm happy. Thanks! – Chris Kohli Jan 8 at 17:05
  • @MartinLezer One of them was me. I'm trying to upvote more questions like this one that provide a summary of work done, a clear problem statement, and a well-chosen code example. It's still a well-asked question regardless of the answer. – David Reed Jan 8 at 17:55
  • @MartinLezer I was one! I up voted on the same notion as of David. – codeyinthecloud Jan 8 at 19:05
2

Moving the trigger to ContentVersion resolved the issue. Example code:

trigger ContentVersion_PreventUpdate on ContentVersion (before update) {

    for ( ContentVersion oldCv : Trigger.old ){

        ContentVersion newCv = Trigger.newMap.get(oldCv.Id);

        if ( oldCv.Title != newCv.Title || oldCv.Description != newCv.Description ){
            newCv.addError('You do not have permission to edit this record.');    
        }
    }
}

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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