Development questions
Write a trigger to prevent users from deleting a file (ContentDocument) if it is attached to an approved Contract.
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
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?