Created
November 13, 2012 01:06
-
-
Save jefftrull/4063200 to your computer and use it in GitHub Desktop.
Test case for deletion of unneeded (childless) parent objects
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
trigger UpdateRelatedObjects on Contact (after update) { | |
// this is meant for reproducing an issue where after the Household lookup on a Contact changes, | |
// empty Households are deleted, and then a Contact's workflow rule evaluation will fail due to | |
// the Household being deleted (despite the fact that it now points to a different Household) | |
// in this experiment TestRelatedObject takes the place of Household, as I have installed the NPSP | |
// in my dev org, and already had TestRelatedObject from a previous experiment | |
// follow code from NPSP (taken off Github): | |
list<id> blankHHDeletes = new list<id>(); | |
List<id> oldHouseholds = new list<id>(); | |
for (Contact c : Trigger.old){ | |
if (Trigger.oldMap.get(c.id).TestRelatedObject__c != null){ | |
oldHouseholds.add(Trigger.oldMap.get(c.id).TestRelatedObject__c); | |
} | |
} | |
Map<id,Integer> oldHouseholdSize = new Map<id, Integer>(); | |
// get HH contact counts with aggregate query | |
AggregateResult[] ar = [select TestRelatedObject__c oldhh, count(id) membercount from Contact where TestRelatedObject__c IN :oldHouseholds group by TestRelatedObject__c]; | |
// create a map from the old household id and its size | |
for (AggregateResult a : ar){ | |
oldHouseholdSize.put((id)a.get('oldhh'), (integer)a.get('membercount')); | |
} | |
// fill out empty households (they will not be present in aggregate results) | |
for (id hhid : oldHouseholds){ | |
if (!oldHouseholdSize.containskey(hhid)) { | |
oldHouseholdSize.put(hhid, 0); | |
} | |
} | |
// put count=0 households into list for deletion | |
List<Id> tbd = new List<Id>(); | |
for (Contact c : Trigger.old){ | |
if ((Trigger.oldMap.get(c.id).TestRelatedObject__c != Trigger.newMap.get(c.id).TestRelatedObject__c) && | |
(oldHouseholdSize.get(Trigger.oldMap.get(c.id).TestRelatedObject__c) == 0)) { | |
tbd.add(Trigger.oldMap.get(c.id).TestRelatedObject__c); | |
} | |
} | |
Database.delete(tbd); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment