How to access an object related lists in apex
I have an object ‘Household Served’ with a field called volunteer, and it also has an Event attached to it. The Event has a related list of Contacts. I need to write a trigger that validates the the volunteer on the Household served object is in the related list of the event.
Currently I have :
|
|
How can I access the Event’s related list of contacts?
Answer
The related list of contacts can be accessed via a sub-select. I’m assuming you are using the standard Contacts object.
You want something like this (this is bulkified, btw)
- Get a list of eventids
- Query events and associated contacts. Put in a map.
- Loop through Household_Server__c
- Get related Event__c from the map.
- Loop through the contacts on the Event__c
- If one matches, you are gold.
Here is the code: