UPDATE: Set Defaults for Opportunity Contact Roles (when converting)
I’ve had a few people reach out regarding an old post about defaulting Opportunity Contact Roles on a Lead convert. Turns out the trigger on Opportunities is not the best option. This was resolved in the comments by having a trigger on Leads instead, but wanted to give the full update in it’s own blog post with updated code. The code below should work and now includes a Test Class too.
Having an AFTER UPDATE trigger on Leads like this is a good way to handle many post-convert needs.
Trigger
trigger Leads on Lead (after update) {
if(Trigger.isAfter && Trigger.isUpdate){
Leads l = new Leads();
l.SetContactRoleDefaults(Trigger.new, Trigger.oldMap);
}
}
Class
public class Leads {
// Sets default values on the Opportunity and Opportunity Contact Role record created during Conversion. Called on AFTER UPDATE
public void SetContactRoleDefaults(Lead[] leads, map<ID,Lead> old_leads)
{
set<ID> set_opptyIDs = new set<ID>();
// Get Opportunity IDs into a Set if the lead was just converted and an Opportunity was created
for (Lead l:leads){
if (l.IsConverted && !old_leads.get(l.id).IsConverted){
if (l.ConvertedOpportunityId != null){
set_opptyIDs.add(l.ConvertedOpportunityId);
}
}
}
// Update Opportunity Contact Roles
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'; // set to what you want defaulted
list_opptyContactRolesToUpdate.add(ocr);
}
if (list_opptyContactRolesToUpdate.size() > 0) {
update list_opptyContactRolesToUpdate;
}
}
}
Test Class
@IsTest
private class Leads_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);
}
}
}