Set Defaults for Opportunity Contact Roles (when converting)
It’s always bugged me that the Primary flag and a Role are not set on Opportunity Contact Roles when converting a Lead. After every convert, I manually set these. Typically, I set the Role to “Decision Maker”and the Primary Flag to True. I got sick of doing this manually, so I wrote a trigger for it and I am sharing it with you all.
Trigger
trigger Opportunities on Opportunity (after insert) { Opportunities o = new Opportunities(); o.SetContactRoleDefaults(Trigger.new); }
Class
public class Opportunities { // Default Constructor public Opportunities() { } // Sets default values on the Contact Role record created during Conversion. Called on AFTER INSERT public void SetContactRoleDefaults(Opportunity[] opptys) { /*************** * Variables ***************/ set<ID> set_opptyIDs = new set<ID>(); /*************** * Initial Loop ***************/ // Get a set of the Opportunity IDs being affected. for(Opportunity o:opptys) { set_opptyIDs.add(o.id); } /*************** * Process Records ***************/ // Update the Contact Role record to be Primary and the Decision Maker list<OpportunityContactRole> list_opptyContactRolesToUpdate = new list<OpportunityContactRole>(); for(OpportunityContactRole ocr:[select Id,IsPrimary,Role from OpportunityContactRole where OpportunityId in :set_opptyIDs]) { ocr.IsPrimary = true; ocr.Role = 'Decision Maker'; list_opptyContactRolesToUpdate.add(ocr); } if (list_opptyContactRolesToUpdate.size() > 0) { update list_opptyContactRolesToUpdate; } } }
Test Class
@isTest private class Opportunities_Test { static testMethod void SetContactRoleDefaults_Test() { // Create a Lead Lead l = new Lead(); l.lastname = 'Lastname'; l.firstname = 'FirstName'; l.company = 'Company'; insert l; // Convert the Lead Database.LeadConvert lc = new database.LeadConvert(); lc.setLeadId(l.id); LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1]; lc.setConvertedStatus(convertStatus.MasterLabel); Database.LeadConvertResult lcr = Database.convertLead(lc); System.assert(lcr.isSuccess()); // Query Contact Role Records and Asserts all was set correctly. for (OpportunityContactRole ocr:[select Id,IsPrimary,Role from OpportunityContactRole where OpportunityId = :lcr.getOpportunityId()]) { system.AssertEquals('Decision Maker', ocr.Role); system.AssertEquals(true, ocr.IsPrimary); } } }