
I'm basically updating all the related Job Addresses of a Contact if the Contact's Other Address is updated.
Trigger ChangeJobAddress on Contact (before update) {
Set<Id> setOfContacts = new Set<Id>();
for(Contact c : Trigger.new){
if(c.Other_Address__c != Trigger.oldMap.get(c.Id).Other_Address__c)
setOfContacts.add(c.Id);
}
if(setOfContacts.size() > 0){
Map<Id, List<sked__Job__c>> ContactJobs = new Map<Id, List<sked__Job__c>>();
List<sked__Job__c> jobsAddress = new List <sked__Job__c>();
jobsAddress = [SELECT Id, JobName, JobType__c,
JobAddress__c,StartDate__c, ContactName__c,
JobLocation__c, JobStatus__c
FROM Job__c
WHERE JobType__c = 'Non-Recurring'
AND JobStart__c > TODAY
AND JobLocation__c = NULL
AND (JobStatus__c != 'Complete')
AND ContactName__c IN :setOfContacts
ORDER BY Name];
for (Job__c job : jobsAddress){
if (ContactJobs.get(job.ContactName__c) == NULL){
ContactJobs.put(job.ContactName__c, new List<sked__Job__c>());
}
ContactJobs.get(job.ContactName__c).add(job);
}
for(Contact con : Trigger.new){
if (ContactJobs.size() > 0){
if (ContactJobs.get(con.Id).size() > 0){
//NEED TO AVOID THIS ONE
for (Job__c j :ContactJobs.get(con.Id)){
string otherStreet = Trigger.oldMap.get(con.Id).OtherStreet;
string otherCity = Trigger.oldMap.get(con.Id).OtherCity;
string otherState = Trigger.oldMap.get(con.Id).OtherState;
string OtherPostal = Trigger.oldMap.get(con.Id).OtherPostalCode;
string addressFormat1 = otherStreet + ', ' + otherCity + ', ' + otherState + ' ' + otherPostal;
string addressformat2 = otherStreet + ', ' + otherCity + ' ' + otherState + ' ' + otherPostal;
if(j.JobAddress__c == addressFormat1 || j.JobAddress__c == addressFormat2){
j.JobAddress__c = con.Other_Address__c;
update j;
}
else {
System.debug('No Job Address updated.');
}
}
}
}
}
}
Change your code to after update and try below
.Trigger ChangeJobAddress on Contact (after update) {
Set<Id> setOfContacts = new Set<Id>();
for(Contact c : Trigger.new){
if(c.Other_Address__c != Trigger.oldMap.get(c.Id).Other_Address__c)
setOfContacts.add(c.Id);
}
if(setOfContacts.size() > 0){
List<sked__Job__c> jobsAddressToUpdate = new List <sked__Job__c>();
List<Contact> lstContacts=[Select id, address fields, (SELECT Id, JobName, JobType__c,
JobAddress__c,StartDate__c, ContactName__c,
JobLocation__c, JobStatus__c
FROM sked__Job__r
WHERE JobType__c = 'Non-Recurring'
AND JobStart__c > TODAY
AND JobLocation__c = NULL
AND (JobStatus__c != 'Complete')
ORDER BY Name )... from contact where id in: setOfContacts];
for(contact c:lstContacts){
if(c.sked__Job__r.size()>0){
for(sked__Job__c a:c.sked__Job__r){
update address field
and add
jobsAddressToUpdate.add(a);
}
}
}
if(!jobsAddressToUpdate.isEmpty()){
update jobsAddressToUpdate;
}
}
}