Skip to main content
Danilo Ong asked in #Apex
So I created a List of List in my Apex Trigger code to list out all service IDs and the Job IDs associated with them. The structure looks like this:

Iterate the items on the List of List created - Apex Trigger Code

The Service object contains the startDate and endDate fields. The Job object also has jobStart and jobEnd date fields.

What I intend to do is, if the dates of a Service record ID are updated, it will loop through all the jobs assigned to that service ID and check if there are dates that are not within the new date duration. This won't allow the user to update the Service record because jobs currently associated with it conflict with the new dates. 
6 answers
  1. Jul 23, 2018, 4:05 AM

    Here is my version of such a trigger

    Trigger checkValidServiceDates on Service__c (after update) {

    Map<Id, List<job__c>> serviceJobs = new Map<Id, List<job__c>>();

    for(job__c serviceJob: [Select Id, Service__c, startDate__c, endDate__c From job__c WHERE Service__c IN :Trigger.newMap.keyset()]){

    if(!serviceJobs.containsKey(serviceJob.Service__c)) {

    serviceJobs.put(serviceJob.Service__c, new List<job__c>());

    }

    serviceJobs.get(serviceJob.Service__c).add(serviceJob);

    }

    for (Service__c service : Trigger.new) {

    List<job__c> jobs = serviceJobs.get(service.Id);

    if (jobs!= null && jobs.size()> 0) {

    for (job__c job : jobs) {

    if (job.startDate__c < service.startDate__c || job.startDate__c > service.endDate__c) {

    service.addError('Existing jobs are out of range of the new service dates');

    }

    if (job.endDate__c < service.startDate__c || job.endDate__c > service.endDate__c) {

    service.addError('Existing jobs are out of range of the new service dates');

    }

    }

    }

    }

    }

     
0/9000