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

**Topic:** Development · **Difficulty:** Hard · **Asked at:** PwC, EY, Infosys · **Tags:** apex-trigger, trigger, coding, scenario, files, validation

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-trigger-to-prevent-users-from-deleting-a-file-contentdocument-if-it-is-attached-to-an-approved

## Answer

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.');
    }
}
```

---
Source: ForceChallenges · last updated 2026-10-19
