function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sfdev1sfdev1 

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
DevAngelDevAngel
Hi sfdev1,

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
sfdev1sfdev1
Thanks  for your input
sfdev1sfdev1
Hi
 
The custom object I created is called CT_Forecase__c. I don't understand why one has to create lookup field to the Opportunity object.
 
I tried to complile the following trigger but it failed
 

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);}


}

sfdev1sfdev1
I tried this but it does not seem to work either
 
trigger TotalOpptyAmountInYear on CT_Forecast__c (before insert) 
{
 for (CT_Forecast__c forecast : System.Trigger.new)
 {
  double dAmountTotal = 0;
  Date dt = System.today().addYears(-1);
  for (Opportunity oppty : [Select Amount From Opportunity Where CloseDate >= :dt])
  {
   dAmountTotal += oppty.Amount;
  }
  forecast.OpptyTotal__c = dAmountTotal;
  Update forecast;
 }
}