
I want to create a Trigger to restrict the deletion of an agreement record if it is currently associated with a job. What I currently have is this, but it pops to all service agreement to be deleted, eventhough the agreement is not associated to a job.
Trigger recordsDeletion on Agreement__c (before delete) {
try{
List <Agreement__c> agreements = new List <Agreement__c>([SELECT Id, ClientName__c FROM Agreement__c]);
List<Job__c> jobsWithAgreements = new List <Job__c> ([SELECT Id, Service_Agreement__c, sked__Contact__c FROM sked__Job__c WHERE Service_Agreement__c != NULL]);
for(Agreement__c sA1 : Trigger.old) {
for (Job__c j: jobsWithServiceAgreements) {
for (Agreement__c sA2 : agreements) {
if(sA2.Id == j.Service_Agreement__c) {
sA2.adderror('Service Agreement is currently associated with a Job and cannot be deleted.');
}
}
}
}
} Catch(Exception ex){
System.debug('\n\n******ERROR DETAILS******\n' + ex.getCause() +'\n'+ ex.getLineNumber() +'\n'+ ex.getMessage() +'\n'+ ex.getStackTraceString());
}
}
Thanks in advance for the help.
Hello Danilo,
I would suggest you to refer the following link for same having many scenarios for the triggers.
1) https://tekslate.com/15-sample-triggers-different-scenarios/
2) Trailhead practice link https://trailhead.salesforce.com/en/modules/apex_triggers/units/apex_triggers_intro
3) refer official document on the samehttps://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers.htm
Thanks & Regards,
Paras Shah