Last active
March 27, 2017 16:26
-
-
Save winniecluk/bc72c3cc93e8efddc3e9d6d48b19e169 to your computer and use it in GitHub Desktop.
trigger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static Set<String> storedTargetIds = new Set<String>(); | |
public static void beforeInsert(List<Referral__c> newList){ | |
List<Target__c> targetsList = [SELECT Id,Start_Date__c,End_Date__c FROM Target__c]; | |
for (Referral__c r : newList){ | |
if (r.Date__c != null){ | |
Date referralDate = r.Date__c; | |
for (Target__c target : targetsList){ | |
if (referralDate > target.Start_Date__c && referralDate <= target.End_Date__c){ | |
r.Target__c = target.Id; | |
// after you find target, add Id to Set | |
storedTargetIds.add(target.Id); | |
} | |
} | |
} // closes outer if | |
} // closes outer for | |
System.debug(storedTargetIds); | |
} | |
public static void afterInsert(List<Referral__c> newList){ | |
Set<Target__c> updateSet = new Set<Target__c>(); | |
List<Target__c> tList = [SELECT Id,User__c,Start_Date__c,End_Date__c,Total_Referrals__c FROM Target__c]; | |
List<AggregateResult> arList = [SELECT count(Id) cnt, Target__c tgt FROM Referral__c WHERE Target__c IN :storedTargetIds GROUP BY Target__c]; | |
for (AggregateResult ar : arList){ | |
// no need for below line | |
// if (ar.get('tgt') != null){ | |
Id targetId = (Id)ar.get('tgt'); | |
Target__c foundTarget=new Target__c(Id=targetId, Total_Referrals__c=(Decimal)ar.get('cnt')); | |
for (Referral__c r : newList){ | |
if (targetId == r.Target__c){ | |
foundTarget.User__c = r.Referred_To__r.OwnerId; | |
} | |
} | |
updateSet.add(foundTarget); | |
// } | |
} | |
if (updateSet.size() > 0){ | |
List<Target__c> updateList = new List<Target__c>(); | |
updateList.addAll(updateSet); | |
update updateList; | |
} | |
} // closes afterInsert |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment