function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Bill BlockBill Block 

Help with first trigger: Creating up to 2 additional contact records on lead convert

Hey all,

I'm hoping someone could help me identify what's wrong with this trigger I wrote. To preface, i'm very new to the Apex development/coding side of SF (only my 2nd week doing this!).

Several agents in the company I work for want to have a way to list up to two additional points of contact on their Lead records that then convert over into Contact records when the Lead is converted. After a week or so of digging into this and searching I feel like i'm close to a solution (but not quite)

Here is the trigger as I have it right now; 0% code coverage currently (it was at one point 77% before I updated the test unit to accompany it)
 
trigger MoreContacts_Trigger on Lead (after update) {

List<Lead> newLeads = trigger.new;
Map<Id, Lead> mOldLeads = trigger.oldMap;
Lead oldLead;

Set<Id> convertedAccountIds = new Set<Id>();
Set<Id> convertedContactIds = new Set<Id>();

for (Lead l : newLeads) {

    if (l.convertedAccountId != null) {
        convertedAccountIds.add(l.convertedAccountId);
    }

    if (l.convertedContactId != null) {
        convertedContactIds.add(l.convertedContactId);
    }
    }

    Account accounts =
    [SELECT Id, Name
     FROM Account
     WHERE Id IN : convertedAccountIds];

for(Lead l : Trigger.New){
If(l.IsConverted){


Contact c1=New Contact(
LastName=l.Secondary_Lead_Contact_Name__c,
Phone=l.Secondary_Lead_Phone__c,
Email=l.Secondary_Lead_Email__c, 
AccountId=accounts.id);

insert c1;

Contact c2=New Contact(
LastName=l.Tertiary_Lead_Contact_Name__c,
Phone=l.Tertiary_Lead_Phone__c,
Email=l.Tertiary_Lead_Email__c, 
AccountId=accounts.id);

insert c2;

}}}

And here is the class (100% code coverage with some help from another developer, was 0% before).
@isTest

public class MoreContacts_TriggerClass{
static testmethod void MoreContacts_TriggerClass(){

Lead Lead = new Lead(
LastName='Test',
Company='TestCompany',
Email='test@test.com',
Phone='9996663333'

);

insert Lead;

Database.LeadConvert lc = new database.LeadConvert();
lc.setLeadId(lead.id);
lc.setDoNotCreateOpportunity(true);
lc.setConvertedStatus('Qualified');

Database.LeadConvertResult lcr = Database.convertLead(lc, false);

}
}

I'm not sure where to go from here but I want to figure out whats wrong, hoping somone might be able to help me pin-point the error. Thanks in advance!
MagulanDuraipandianMagulanDuraipandian
Hi,
Try to avoid using SOQL and DML inside a for loop. Setting accounts.Id is incorrect.

Check the below sample trigger

trigger LeadTrigger on Lead ( after update ) {

    List < Contact > listContacts = new List < Contact >();
    
    for( Lead objLead : trigger.new ) {
    
        if ( objLead.IsConverted && !trigger.oldMap.get( objLead.Id ).IsConverted ) {
            
            Contact agent1 = new Contact( LastName = 'Agent1' );
            agent1.AccountId = objLead.ConvertedAccountId;
            listContacts.add( agent1 );
            Contact agent2 = new Contact( LastName = 'Agent2' );
            agent2.AccountId = objLead.ConvertedAccountId;
            listContacts.add( agent2 );
        
        }
        
    }
    
    if ( listContacts.size() > 0 )
        insert listContacts;

}
--
Magulan Duraipandian
www.infallibletechie.com
 
Bill BlockBill Block
Hi Magulan,

Thank you so much for your response! The trigger worked per the example you provided (with my own values) and I was able to convert a lead in my sandbox to an account with three contact records!!! 

I'm however running into a problem getting code coverage on this trigger itself!! It's stuck at 0%.
 
trigger CreateMoreLeadContacts on Lead (after update) {

list < Contact > listContacts = new List < Contact>();

for(Lead objLead : trigger.new) {

if(objlead.IsConverted && !trigger.oldMap.get(objLead.Id).IsConverted) {

Contact c1=New Contact(
LastName=objLead.Secondary_Lead_Contact_Name__c,
Phone=objLead.Secondary_Lead_Phone__c,
Email=objLead.Secondary_Lead_Email__c);

c1.AccountId = objLead.ConvertedAccountId;
listContacts.add(c1);

Contact c2=New Contact(
LastName=objLead.Tertiary_Lead_Contact_Name__c,
Phone=objLead.Tertiary_Lead_Phone__c,
Email=objLead.Tertiary_Lead_Email__c);

c2.AccountId = objLead.ConvertedAccountId;
listContacts.add(c2);

     }
        
    }
    
    if ( listContacts.size() > 0 )
        insert listContacts;

}
How would I best write a class for this to get coverage? 

All the best,

Bill
 
MagulanDuraipandianMagulanDuraipandian
Below code worked for me

@isTest  
private class LeadTriggerTest {  
      
    static testMethod void testLeadConv() {  
          
        Lead objLead = new Lead( FirstName = 'Test', LastName = 'Sample', Company = 'Testing Sample Co' );  
        insert objLead;  
          
        Database.LeadConvert lc = new database.LeadConvert();  
        lc.setLeadId( objLead.Id );  
        lc.setDoNotCreateOpportunity( true );  
        lc.setConvertedStatus( 'Closed - Converted' );  
          
        Database.LeadConvertResult lcr = Database.convertLead(lc, false);  
          
        system.debug( 'Errors are ' + lcr.getErrors() );  
          
        system.assert( lcr.isSuccess() );  
          
        List < Contact > listContacts = [ SELECT Id FROM Contact WHERE Name LIKE 'Agent%' ];  
        system.assert( listContacts.size() == 2 );  
          
    }  
  
}  
Bill BlockBill Block
Hi Magulan,

Thank you so much for your help. This is really helping me learn.

Unfortunately the class didn't work for me. The error/stacktrace is telling me that the system.assertexception Failed | Class.LeadTriggerTest.testLeadConv: line 18, column 1

I didn't change anything in the triggers/class except for the custom field variables (secondary/tertiary contact name, email, phone)

Would I need to add these custom fields to the class in order for it to pass? 

Trigger as of right now (changed agent1 / agent2 to c1 / c2)
 
trigger LeadTrigger on Lead (after update) {

list < Contact > listContacts = new List < Contact > ();

for(Lead objLead : trigger.new) {

if(objlead.IsConverted && !trigger.oldMap.get(objLead.Id).IsConverted) {

Contact c1=New Contact(
LastName=objLead.Secondary_Lead_Contact_Name__c,
Phone=objLead.Secondary_Lead_Phone__c,
Email=objLead.Secondary_Lead_Email__c);

c1.AccountId = objLead.ConvertedAccountId;
listContacts.add(c1);

Contact c2=New Contact(
LastName=objLead.Tertiary_Lead_Contact_Name__c,
Phone=objLead.Tertiary_Lead_Phone__c,
Email=objLead.Tertiary_Lead_Email__c);

c2.AccountId = objLead.ConvertedAccountId;
listContacts.add(c2);

     }
        
    }
    
    if ( listContacts.size() > 0 )
        insert listContacts;

}


Class as of right now  (I changed Agent% to c%)
 
@isTest  
private class LeadTriggerTest {  
      
    static testMethod void testLeadConv() {  
          
        Lead objLead = new Lead( FirstName = 'Test', LastName = 'Sample', Company = 'Testing Sample Co' );  
        insert objLead;  
          
        Database.LeadConvert lc = new database.LeadConvert();  
        lc.setLeadId( objLead.Id );  
        lc.setDoNotCreateOpportunity( true );  
        lc.setConvertedStatus( 'Converted' );  
          
        Database.LeadConvertResult lcr = Database.convertLead(lc, false);  
          
        system.debug( 'Errors are ' + lcr.getErrors() );  
          
        system.assert( lcr.isSuccess() );  
          
        List < Contact > listContacts = [ SELECT Id FROM Contact WHERE Name LIKE 'c%' ];  
        system.assert( listContacts.size() == 2 );  
          
    }  
  
}


 

Thank you again!!