
Force.com Cookbook Sample Code
Chapter 4: Best Practices for Writing Apex - Comparing Queries Against Trigger.old and Trigger.new
To download all the code samples, access the Cookbook. -
This Apex trigger demonstrates how to correlate records and query results with the Trigger.newMap and Trigger.oldMap ID-to-SObject maps. This trigger uses Trigger.oldMap to create a set of unique IDs (Trigger.oldMap.keySet()). The set is then used as part of a query to create a list of job applications associated with the candidates being processed by the trigger. For every job application returned by the query, the related candidate is retrieved from Trigger.oldMap and prevented from being deleted.
trigger candidateTrigger on Candidate__c (before delete) {
for (Job_Application__c jobApp : [SELECT Candidate__c FROM Job_Application__c
WHERE Candidate__c IN :Trigger.oldMap.keySet()]) {
Trigger.oldMap.get(jobApp.Candidate__c).addError('Cannot delete candidate with a job application');
}
}
Sample code provided by salesforce.com. All rights reserved.