+ Start a Discussion
pierrefrazny.ax358pierrefrazny.ax358 

AggregateResult for loop issue

Hello,

I wrote a class which caculates the number of instance of  a custom object called Volunteer_Registration__c to Contact. This class is called by a trigger on Volunteer_Registration__c (after detele, after insert). It works great except for one scenario: when I delete the last Volunteer Registration record, I expect the the field  'of_Volunteer_Visit__c' to be reset to zero or at least NULL but this does not work. Basically it looks like in this specific scenario the for loop is not executed.

Any idea how I could modify my code to accomodate this scenario?

 

public with sharing class RollupContactInformation {

	public static void DoIndVisit(Set<ID> contIDs) {
                
    	Contact[] updateContacts = new Contact[]{};
        
        Map<ID, Contact> contacts = new Map<ID, Contact>([SELECT Id FROM Contact WHERE Id in: ContIDs ]);
                        
        //Loop over the aggregate result set
	for (AggregateResult ar : [select Contact__c, COUNT(Id)numVisits From Volunteer_Registration__c Where Contact__c in: ContIDs and Status__c = 'Completed' AND Inquiry_Type__c = 'Individual' group by Contact__c ]) 
		{	
			
		Contact thisContact = new Contact(Id=String.valueOf(ar.get('Contact__c')));
		thisContact.of_Volunteer_Visit__c = Integer.valueOf(ar.get('numVisits')); 
				
		//Add this new account to the list of account objects
		updateContacts.add(thisContact);
		}

		//Update the account object.
		if(updateContacts.size()>0) {update updateContacts;}	
        }
}

 Thanks   a lot.

Pierre