Groovy 30 – Add Opportunity Account Contacts as Opportunity Contacts
Add Opportunity Contacts
This script will help you add all the opportunity account contacts to the opportunity. This ensures the opportunity has the same contacts as the Account linked to it.
Go to App Composer > Sales > Opportunity > Server Scripts and create a new Object Trigger of type Before Insert In Database.
Groovy Code
// Groovy Code Snippet if (TargetPartyId != null) { def accountContacts = []; def OpportunityContacts = []; def primaryAccountContact = Organization?.PreferredContactPersonId; def relationship = Organization?.Relationship; while (relationship.hasNext()) { def resourceRow = relationship.next(); if (resourceRow.RelationshipType == 'CONTACT') { accountContacts.add(resourceRow.ObjectId); } } // Get Opportunity Contacts def optyResource = OpportunityContact; while (optyResource.hasNext()) { def row = optyResource.next(); OpportunityContacts.add(row.PartyId); } for (int i = 0; i < accountContacts.size(); i++) { def x = 0; for (String y : OpportunityContacts) { if (y.contains(accountContacts[i].toString())) { x++; } } if (x == 0) { def var_insertRow = optyResource.createRow(); var_insertRow.setAttribute('PERPartyId', accountContacts[i]); if (primaryAccountContact != null && primaryAccountContact == accountContacts[i]) { var_insertRow.setAttribute('PrimaryFlg', 'Y'); } optyResource.insertRow(var_insertRow); } x = 0; } }
Expected Behavior
The trigger will execute each time an opportunity is created. It will check if the opportunity has an account associated with it. If it does, it will collect all those account contacts and add them to the opportunity contacts, setting the primary opportunity contact to the same contact as the Account's primary contact.
If the opportunity creation does not have an account, the script will do nothing.