Skip to content

Instantly share code, notes, and snippets.

@charltonAthletic
Last active August 29, 2015 14:16
Show Gist options
  • Save charltonAthletic/959347734dea7e64b246 to your computer and use it in GitHub Desktop.
Save charltonAthletic/959347734dea7e64b246 to your computer and use it in GitHub Desktop.
// Typically you would use Batch Apex for this or if you wanted it via a trigger, it would utilize a helper class. Nonetheless, the code may be useful.
trigger NumberOfApprovedContracts on Contract (after delete, after insert, after update, after undelete) { // trigger context variables
Set<Id> toUpdateAccIds = new Set<Id>();
//Set<Id> zeroAccIds = new Set<Id>();
// IF CONTRACT CREATED OR UNDELETED, FOR ALL THESE CONTRACTS, IF APPROVED THEN ADD CONTRACT ACCOUNT ID TO THE SET
if(Trigger.isInsert || Trigger.isUndelete) {
for(Contract c : Trigger.new) {
if(c.RecordType_Name__c == 'Approved Contract' ) { // could use dynamic/database search instead
toUpdateAccIds.add(c.AccountId);
}
}
}
// IF CONTRACT IS UPDATED, FOR ALL THESE CONTRACTS, IF THE RECORD TYPE CHANGED AND NOW IS APPROVED, THEN ADD CONTRACT IDS TO THE LIST
if(Trigger.isUpdate) {
for(Contract c : Trigger.new) {
if(Trigger.oldMap.get(c.Id).RecordType_Name__c != c.RecordType_Name__c && c.RecordType_Name__c == 'Approved Contract') {
toUpdateAccIds.add(c.AccountId);
}
// in case of a reparent you'll need to recalculate the other account as well
// since we are adding them to a set of Id's dupes are ommited anyway
if(Trigger.oldMap.get(c.Id).AccountId != c.AccountId) { // IF ACCT ID NO LONGER = ACCT ID (REPARENT) THEN...
toUpdateAccIds.add(c.AccountId);
toUpdateAccIds.add(Trigger.oldMap.get(c.Id).AccountId);
//zeroAccIds.add(Trigger.oldMap.get(c.Id).AccountId);
}
}
}
// delete needs recalc
if(Trigger.isDelete) {
for(Contract c : Trigger.old) {
toUpdateAccIds.add(c.AccountId);
}
}
List<Account> affectedAccs = [select (select id from Contracts where RecordType_Name__c = 'Approved Contract') from Account where Id IN :toUpdateAccIds];
for(Account a : affectedAccs) {
// for count
a.Total_Approved_Contracts__c = a.Contracts.size();
// for true/false
if(a.Contracts.size()>0) {
a.Approved_Contracts__c = true;
} else {
a.Approved_Contracts__c = false;
}
}
if(affectedAccs.size()>0) {
update affectedAccs;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment