Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Test case for deletion of unneeded (childless) parent objects
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( != null){
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( != Trigger.newMap.get( &&
(oldHouseholdSize.get(Trigger.oldMap.get( == 0)) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.