public with sharing class SyncRepairFromMCAETrigger { public static void syncRepair(List newList, Map newMap, List oldList, Map oldMap) { if (Trigger.isBefore) { List mcId = new List (); if (Trigger.isInsert || Trigger.isUpdate) { for (Repair__c r : newList) { // if (String.isBlank(r.Maintenance_Contract__c) == false) { if (String.isBlank(r.Maintenance_Contract__c) == false && (Trigger.isInsert || Trigger.isUpdate && r.Maintenance_Contract__c != oldMap.get(r.Id).Maintenance_Contract__c)) { mcId.add(r.Maintenance_Contract__c); } } } List mceId = new List (); List mcList = new List (); List mcaeList = new List (); if (mcId.size() > 0) { mcList = [SELECT Id, Estimation_Id__c FROM Maintenance_Contract__c WHERE Id IN:mcId]; } //if (mcList.size() > 0) { // for (Maintenance_Contract__c mc : mcList) { // if (String.isBlank(mc.Estimation_Id__c) == false) { // mceId.add(mc.Estimation_Id__c); // } // } //} //if (mceId.size() > 0) { // mcaeList = [SELECT Id, Asset__c, Maintenance_Contract_Estimate__c, Maintenance_Contract_Estimate__r.Maintenance_Contract__c FROM Maintenance_Contract_Asset_Estimate__c WHERE Maintenance_Contract_Estimate__c IN : mceId]; //} if (mcId.size() > 0) { mcaeList = [SELECT Id, Asset__c, Maintenance_Contract_Estimate__c, Maintenance_Contract_Estimate__r.Maintenance_Contract__c FROM Maintenance_Contract_Asset_Estimate__c WHERE Maintenance_Contract_Estimate__r.Maintenance_Contract__c IN : mcId AND Maintenance_Contract_Estimate__r.IsSyncing__c = True]; } if (mcaeList.size() > 0) { for (Repair__c rpr : newList) { if (String.isBlank(rpr.Maintenance_Contract__c) == false) { for (Maintenance_Contract_Asset_Estimate__c mcae : mcaeList) { if (rpr.Maintenance_Contract__c == mcae.Maintenance_Contract_Estimate__r.Maintenance_Contract__c && rpr.Delivered_Product__c == mcae.Asset__c) { rpr.Maintenance_Contract_Asset_Estimate__c = mcae.Id; break; } } } } } } } }