Skip to content

Instantly share code, notes, and snippets.

Created December 4, 2014 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/09d02f388683179319fb to your computer and use it in GitHub Desktop.
Save anonymous/09d02f388683179319fb to your computer and use it in GitHub Desktop.
add primary contact to opportunity
trigger AddPrimaryContactToOpp on Opportunity (before insert, before update) {
// THIS TRIGGER WILL OVERWRITE ANY CONTACT DEFINED IN THE CUSTOM FIELD CONTACT__C ON THE OPPORTUNITY OBJECT.
// SET THIS FIELD TO READ ONLY OR CHANGE THE FUNCTIONALITY BELOW TO AVIOD DATA BEEING OVERWRITTEN BY MISTAKE...
for (Opportunity o : Trigger.new) {
// o.NextStep = 'DEBUG: Running function...';
// CREATE ARRAY OF ALL CONTACT ROLES ON THIS OPPORTUNITY. THE REASON WHY WE DONT PICK THE PRIMARY CONTACT ROLE ONLY
// IS BECAUSE THE PRIMARY FLAG IS NOT SET WHEN LEADS ARE CONVERTED TO OPPORTUNITIES. ONLY WHEN CREATING OPPORTUNITIES
// MANUALLY FROM THE CONTACT OBJECT THE IS PRIMARY CHECKBOX IS CHECKED...
OpportunityContactRole[] contactRoleArray =
[select ContactID, isPrimary from OpportunityContactRole where OpportunityId = :o.id ORDER BY isPrimary DESC, createdDate];
if (contactRoleArray.size() > 0) {
// IF PRIMARY IS DEFINED THEN THIS WILL BE THE FIRST OBJECT. IF NOT THE FIRST ADDED CONTACT ROLE WILL BE ADDED...
o.Contact__c = contactRoleArray[0].ContactID;
}else{
// IF NO CONTACT ROLES EXIST RETURN NULL...
o.Contact__c = null;
// o.NextStep = 'DEBUG; CONTACT = null ';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment