[SalesForce] How to populate contact roles based on a custom lookup field in Opportunities for the Primary Contact

Our current sales process has a lead converted to an opportunity. There is a custom lookup field on the Opportunity to identify the primary point of contact. Once that lookup field is populated, we have a custom field to populate the email address of that contact in order to have an email alert set up. Question here is, if that lookup field is populated with the contact, is there a way we can also leverage some automation to assign it as primary and add them under Contact Roles related list in the Opportunity?

Best Answer

In addition, to using a Process Builder and a Flow based solution, an alternative could be to use an after update Apex Trigger.

Refer the following sample Apex Trigger code and build upon this.

trigger OpportunityTrigger on Opportunity (after update) {

    if(Trigger.isAfter){

        if(Trigger.isUpdate){

            List<OpportunityContactRole> oppContactRoleList = new List<OpportunityContactRole>();

            for(Opportunity newOppRecord :Trigger.new){

                //This condition could be optimized to check if an existing OCR already exists and accordingly perform an upsert
                if(Trigger.newMap.get(newOppRecord.Id).Id <> Trigger.oldMap.get(newOppRecord.Id).Id){

                    oppContactRoleList.add(
                        new OpportunityContactRole(
                            OpportunityId = 'Your_Opp_Id', 
                            ContactId='Your_Contact_Id', 
                            Role = 'Decision Maker');
                    );

                }

            }//for

            if(oppContactRoleList.size() > 0){
                Database.insert(oppContactRoleList);
            }
        }//isUpdate
    }//isAfter

}//OpportunityTrigger ends

Although I would recommend using the ProcessBuilder and Flow based approach stated above since, that will save you the overhead of writing test code.

Related Topic