Development questions

Write a trigger to prevent users from deleting a file (ContentDocument) if it is attached to an approved Contract.

DevelopmentHardPwCEYInfosys

Write a before delete trigger on ContentDocument, find its links to Contracts, and block deletion if the Contract is approved (e.g. Status = 'Activated' or a custom approval field).

apex
trigger ContentDocTrigger on ContentDocument (before delete) {
    Set<Id> contractIds = new Set<Id>();
    Map<Id, Id> docByContract = new Map<Id, Id>();
    for (ContentDocumentLink l : [SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink
                                  WHERE ContentDocumentId IN :Trigger.oldMap.keySet()]) {
        if (l.LinkedEntityId.getSObjectType() == Contract.SObjectType) docByContract.put(l.LinkedEntityId, l.ContentDocumentId);
    }
    for (Contract c : [SELECT Id FROM Contract WHERE Id IN :docByContract.keySet() AND Status = 'Activated']) {
        Trigger.oldMap.get(docByContract.get(c.Id)).addError('Files on an approved Contract cannot be deleted.');
    }
}
apex-triggertriggercodingscenariofilesvalidation