Archive for June, 2012

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 Leads on Lead (after update) {
    if(Trigger.isAfter && Trigger.isUpdate){
        Leads l = new Leads();
        l.SetContactRoleDefaults(, Trigger.oldMap);



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({
			if (l.ConvertedOpportunityId != null){
	// 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
	if (list_opptyContactRolesToUpdate.size() > 0) {
		update list_opptyContactRolesToUpdate;


Test Class

private class Leads_Test {

static testMethod void SetContactRoleDefaults_Test() {
    // Create a Lead
    Lead l = new Lead();
    l.lastname = 'Lastname';
    l.firstname = 'FirstName'; = 'Company';
    insert l;
    // Convert the Lead
    Database.LeadConvert lc = new database.LeadConvert();
    LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1];
    Database.LeadConvertResult lcr = Database.convertLead(lc);
    // 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);


Comments (5) comments feed