please bear with me as I'm new to Apex and triggers.
I have a custom object, Conferences. This custom object is the master to a custom Junction object, Junction. That Junction object is set up to allow me to show a related list of standard object Contacts and thus relate the Contacts to the Conferences.
I'm attempting to create an Apex Trigger that will fire after insert, after update, after delete, and after undelete of contacts assigned to the Conference through the Junction object. All the trigger needs to do is update a field on the Conferences object showing a count of the number of Contacts associated with the Conference.
I feel like I must be making this harder than it needs to be. I'm struggling with the data modeling for this task - I'm assuming my trigger would need to be on the Junction object since that's where the count of Contacts would be, so I'd assume my code would start:
trigger ConferenceAttendeesUpdater on Junction__c (after insert, after update, after delete, after undelete ) {
That seems like sloppy code, since I'm thinking that reads anytime the junction object is updated the trigger will fire, when really the only time it needs to is when the count of Contacts changes. For some reason I'm having trouble conceptually grasping what methods I'd need. I'm thinking it would include Junction__c.Contacts.size() for the count of Contacts assigned to the conference?
Any help would be greatly appreciated.
Yes, if you want to count the number of Junction__c records related to a Contact, you would put the trigger on the Junction__c object. Best practice is to put your logic in a Class not in the Trigger. Below is a rough implementation of what you want.