+ Start a Discussion

Triggers on junction objects

I noticed that triggers aren't allowed on OpportunityContactRole yet. Having triggers on OpportunityContactRole, CampaignMember, and the like is crucial to being able to enforce business processes end to end.

For example, I wrote a sample trigger that rolls up Opportunity Amounts to the primary Contacts on those Opps. This shows the revenue history for a Contact, and is really helpful to the groups I build databases for. But a person's OppContactRole can be deleted, changed, or added without triggering the code that will re-tally the Amounts, and the roll-ups will drift from the correct value.

If I can put a similar trigger on OppContactRole, it will be impossible for the tally to get out of date, as long as I've built two good triggers.

Apex is great stuff. Amazingly simple and powerful. Just wanted to pass on this initial thought.


Brock ElgartBrock Elgart

You can write the trigger on Contact:

1. Every time the contact is updated check if the amount field changed. If so query all related Opportunity Contact role records where the role is primary.

2. From there add the opportunity ID's from the OpportunityContact records to a set.

3. Query all OpportunityContactRole records whose Opp Id is in the set and whose role is primary.

4. For each ID in the set:
-Totally re-evelaute the amount rollup
-Set of opportunities to update.add(New Opportunity(ID = loop variable, AMount_Rollup__c = CalculatedValue)

5. Update the set of opportunities marked for update