# Write a trigger on ContentDocumentLink (File upload) to check if a file is uploaded to a Case and update Has_Attachment__c = true on the Case.

**Topic:** Development · **Difficulty:** Medium · **Asked at:** Deloitte, Cognizant, Capgemini · **Tags:** apex-trigger, trigger, coding, scenario, files

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-trigger-on-contentdocumentlink-file-upload-to-check-if-a-file-is-uploaded-to-a-case-and-update-has

## Answer

Files are linked to records through `ContentDocumentLink` (the `LinkedEntityId` is the Case Id). Use `after insert` and check the Case key prefix (`500`).

```apex
trigger CDLTrigger on ContentDocumentLink (after insert) {
    Set<Id> caseIds = new Set<Id>();
    for (ContentDocumentLink l : Trigger.new) {
        if (l.LinkedEntityId != null && l.LinkedEntityId.getSObjectType() == Case.SObjectType) caseIds.add(l.LinkedEntityId);
    }
    if (caseIds.isEmpty()) return;
    List<Case> cases = new List<Case>();
    for (Id id : caseIds) cases.add(new Case(Id = id, Has_Attachment__c = true));
    update cases;
}
```
You can't write a trigger directly on `ContentDocument` for the upload link itself, since the link is created by ContentDocumentLink.

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