@venkateswarlu Allipudi
Check the below trigger :
trigger PreventCaseDeletion on Case (before delete) {
// Set to store IDs of Cases being deleted to minimize the query scope
Set<Id> caseIdsBeingDeleted = Trigger.oldMap.keySet();
// Query to find Cases that are being deleted and are related to both an Account and a Contact
List<Case> casesWithAccountAndContact = [
SELECT Id
FROM Case
WHERE Id IN :caseIdsBeingDeleted
AND AccountId != null
AND ContactId != null
];
// Set to store the IDs of Cases that meet the criteria for prevention
Set<Id> preventDeletionCaseIds = new Set<Id>();
for (Case c : casesWithAccountAndContact) {
preventDeletionCaseIds.add(c.Id);
}
// Loop through the Cases in Trigger.old to find matches and prevent deletion
for (Case c : Trigger.old) {
if (preventDeletionCaseIds.contains(c.Id)) {
// Prevent deletion by adding an error to the Case record
c.addError('Cannot be deleted because it is related to both an Account and a Contact.');
}
}
}
4 risposte