You need to sign in to do that
Don't have an account?
Count Related Records using Apex Trigger
Hi all,
I have two Parent records that share the same Child record. I would like to be able to count the number of related Child records. Neither are master-detail records, hence the requirement for an Apex Trigger.
I have a working count trigger for the Parent records (included below for referece), but I suspect I need another trigger on the Child records in order for the Count trigger to fire?
The other question: An attendee (Child record) can be removed from an Event or Group without the record being deleted. A user will edit the Attendee and clear the lookup field. Is this possible to include in the same Child trigger to fire the Count Trigger on the Parent?
I'm fairly new to triggers :)
Event - Parent
Group - Parent
Attendee - Child
trigger CountRelatedAttendees on event_c__c (before insert, before update) { event_c__c[] s = Trigger.new; String sid = null; Sid = s[0].id; Integer i = [select count() from attendees__c where Event_no__c = :sid]; s[0].Places_used__c = i; }
Can the below be done on attendees ?
This should update the Parent record..
Regards,
Thanks for the input!
I am getting the error
Apologies this may be a silly question but what is the <Event ID> part in your code? I presume this is not the Id of the event record but something APEX specific?
Actually I am getting there, the code below works now. However if the Attendee is removed from the event (so the lookup field is cleared but the Attendee record is not deleted), I get the error below:
UpdateRelatedAttendees: execution of AfterUpdate
caused by: System.ListException: List index out of bounds: 0
Trigger.UpdateRelatedAttendees: line 15, column 7
Is this close to something that you're looking for? If it's unreadable, PM me and we can talk this over, but it should be fairly readable....
There's plenty of optimization to be done here but....without talking in more detail about the actual requirements...I don't even know if this is what you need!
Apologies for taking a couple of days to reply, but your trigger works as intended! I had to swap some object/relationship names, but otherwise I did not have to edit any of the actual code.
The part I could not get working was updating the Parent records when the Child was removed or deleted - but your solution has fixed that for me. Now I just have to write the Apex test code...
Thanks for you help, greatly appreciated :)
Ah, apologies it appears I missed something...the places used is not updating on either Parent when the Child has the related lookup fields updated to null.
In that case you need to do some extra checks in a before trigger, getting all the ids of the parents from records that are getting their lookups set to null, and populating the sets with those as well. The counting logic is still the same.