You need to sign in to do that
Don't have an account?
sfdev1
Trigger that sums up Opportunities for the last 12 months
I waht to create a cutom forecast object that when I add a new record it will fire off Apex Trigger to will collect sum up all the Opportunities into a single text field. The Salesrep enter this forecase base on this figure.
How would I create this trigger?
Could somebody sent me some sample code?
Thanks
Stephen
Well, create an after update on your custom object. In a loop that iterates over the custom objects supplied by the trigger, collect the oppty ids for each object and save them in a map keyed on the custom object id. Your custom object is indicated by Object__c and Object__r. You should use the correct name instead. Also, you should create a lookup relationship from the Opportunity object to your custom object.
Map objectIds = new Map(Trigger.new);
Execute a query to retrieve all the opptys into a map something like the following
Map opptyMap = new Map();
for (Opportunity oppty : [Select Id, Amount, Object__r.Id From Opportunity Where Object__r.Id in :objectIds.keySet() and CreatedDate >= PAST_12_MONTHS]) {
if (!opptyMap.containsKey(oppty.Object__r.Id)) {
opptyMap.put(oppty.Object__r.Id, oppty.Amount);
} else {
opptyMap.get(oppty.Object__r.Id) = opptyMap.get(oppty.Object__r.Id) + oppty.Amount;
}
Now you can loop over your first map and update the values:
for (Object__c o : objectIds) {
o.OpptyTotal = opptyMap.get(o.Id);
}
This code is not actually tested, but this is the pattern you should use.
Cheers
trigger GetAnnualSum on CT_Forecast__c () {
Map objectIds = new Map(Trigger.new);
Map opptyMap = new Map();for (Opportunity oppty : [Select Id, Amount, CT_Forecast__r.Id From Opportunity Where CT_Forecast__r.Id in objectIds.keySet() and CreatedDate >= PAST_12_MONTHS]) {if (!opptyMap.containsKey(oppty.Object__r.Id)) {opptyMap.put(oppty.Object__r.Id, oppty.Amount);} else {opptyMap.get(oppty.Object__r.Id) = opptyMap.get(oppty.Object__r.Id) + oppty.Amount;}
for (CT_Forecast__c o : objectIds) {o.OpptyTotal = opptyMap.get(o.Id);}
}