Skip to content

Instantly share code, notes, and snippets.

@capeterson
Created September 10, 2011 00:13
Show Gist options
  • Save capeterson/1207674 to your computer and use it in GitHub Desktop.
Save capeterson/1207674 to your computer and use it in GitHub Desktop.
trigger CountIncidents on itil_b__Incident__c (after insert, after update){
List<Id> AccountIDs = itil_b.Util.getIDFields(Trigger.new,'itil_b__account__c');
List<AggregateResult> totalIncidents = [SELECT itil_b__Account__c, COUNT(Id)
FROM itil_b__Incident__c WHERE itil_b__Account__c IN :AccountIDs AND itil_b__Account__c != null
GROUP BY ROLLUP(itil_b__Account__c)];
Map<id,Account> accounts = new Map<id,Account>([SELECT total_incidents__c, id FROM Account WHERE Id IN :accountIDs]);
for(AggregateResult ar: totalIncidents){
Id accountId = (id) ar.get('itil_b__Account__c');
if(accountId == null)
continue; //this aggregate result isn't for a specific account, skip it.
Integer incidentCount = (Integer) ar.get('expr0');
Account a = accounts.get(accountId);
a.total_incidents__c = incidentCount;
}
update accounts.values();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment