+ Start a Discussion
Sainath VenkatSainath Venkat 

lead conversion trigger causing issue when multiple records are inserted

Hello everyone,

I wrote a trigger that will create records in multiple objects and then converts it but when I insert multiple records then its showing below error.

"ContactCreationFromLead: execution of BeforeUpdate
caused by: System.ListException: List index out of bounds: 3"

My trigger is below.

 
trigger ContactCreationFromLead on Lead (After insert, before Update) {
    //trigger to create contact, relationship, affiliation records from lead.
    List<Lead> em = new List<Lead>();
    List<Contact> conInsertList = new List<Contact>();
    List<hed__Affiliation__c> affiliation = new List <hed__Affiliation__c>();
    List<hed__Relationship__c> relation = new List<hed__Relationship__c>();
    List<hed__Affiliation__c> affiliationListToBeInserted = new List<hed__Affiliation__c>();
    List<String> listEmail = new List<String>();
    List<String> listname = new List<String>();
    Set<String> otherProgramsValueSet = new Set<String>();
    if(trigger.isInsert || trigger.isUpdate){
    for (Lead em : Trigger.new) {
        if(em.Email != null){
            listEmail.add(em.Email);
        }
        if(em.What_is_your_primary_program_of_interest__c != null ){
            listname.add(em.What_is_your_primary_program_of_interest__c);
        }
        if(em.Other_Programs_of_Interest__c != null){
            otherProgramsValueSet.addAll(em.Other_Programs_of_Interest__c.split(';'));
        }
    }
    }
    //to catch the account Id that matches the lead primary program of interest
    //account name should match with primary program of interest picklist values
    List<Account> account = [SELECT Id,Name,Pardot_Program_Name__c from Account WHERE Pardot_Program_Name__c = :listname];
    string record;
    for(Account acc : account){
        record = acc.Id; 
    }
    List<Contact> cem = [SELECT Id, Email FROM Contact WHERE Email = :listEmail];
    String cemail;
    for(Contact ce : cem){
        cemail = ce.Email;
    }
    Id recordtype1 = [select Id From RecordType WHERE DeveloperName='Lead'].Id;
    Id recordtype2 = [select Id From RecordType WHERE DeveloperName='Parent'].Id;
    //code to create contact for student if form is filled by student
    for(Lead ld : Trigger.new) {
        if (ld.Email != cemail && ld.Parent_or_guardian__c == false) {
            
            Contact cnt = new Contact();           
                cnt.FirstName = ld.FirstName;
                cnt.LastName = ld.LastName;
                cnt.Email = ld.Email;
            conInsertList.add(cnt);
        }
        //code to create contacts for parent and student if form is filled by parent
        else{
            if(ld.Email != cemail && ld.Parent_or_guardian__c == true ){
                Contact cnt1 = new Contact();
                cnt1.RecordTypeId = recordtype2;
                cnt1.FirstName = ld.Parent_First_Name__c;
                cnt1.LastName = ld.Parent_Last_Name__c;
                cnt1.Email = ld.Parent_Email__c;
            conInsertList.add(cnt1);
                Contact cnt2 = new Contact();
                cnt2.RecordTypeId = recordtype1;
                cnt2.FirstName = ld.FirstName;
                cnt2.LastName = ld.LastName;
                cnt2.Email = ld.Email;
            conInsertList.add(cnt2);
            }
        }
    }
    if(conInsertList.size()>0){
        INSERT conInsertList;
        List<Id> conInsert = new List<Id>();
        //catch the inserted contact ids to create relationship record
        if(conInsertList.size()>1){
        for(Integer i = 0, s = conInsertList.size(); i < s; i += 2){
            //creates relation record by catching current student and parent record id's
            hed__Relationship__c hedrel = new hed__Relationship__c();
            hedrel.hed__Contact__c = conInsertList[i + 1].Id;
            hedrel.hed__RelatedContact__c = conInsertList[i].Id;
            hedrel.hed__Type__c = 'Parent';
            relation.add(hedrel);
            //creates affiliation record if filled by parent
            if( listname.isEmpty()==false && record != null){
            hed__Affiliation__c hedaff = new hed__Affiliation__c();
            hedaff.hed__Account__c = record;
            hedaff.hed__Contact__c = conInsertList[i + 1].Id;
            hedaff.hed__Primary__c = true;
            affiliation.add(hedaff);
            }
            //creates affiliation records for other programs multi select picklist field
            if(otherProgramsValueSet != null){
            Map<String,Id> accNamesToIdsMap = new Map<String,Id>();
            for(Account acc : [select id,Pardot_Program_Name__c from account where Pardot_Program_Name__c in : otherProgramsValueSet]){
                accNamesToIdsMap.put(acc.Pardot_Program_Name__c,acc.Id);
            }
                for(Id accId : accNamesToIdsMap.values()){
                  affiliationListToBeInserted.add(new hed__Affiliation__c(hed__Account__c= accId,
                                                           hed__Contact__c=conInsertList[i + 1].Id));
                }
            }
        }
        }
        else{
            //creates Affiliation record if filled by student only
            if(conInsertList.size()==1){
            for(Integer i = 0, s = conInsertList.size(); i < s; i += 2){
                if( listname.isEmpty()==false && record != null){
            hed__Affiliation__c hedaff = new hed__Affiliation__c();
            hedaff.hed__Account__c = record ;
            hedaff.hed__Contact__c = conInsertList[i].Id;
            hedaff.hed__Primary__c = true;
            affiliation.add(hedaff);
                }
                if(otherProgramsValueSet != null){
                Map<String,Id> accNamesToIdsMap = new Map<String,Id>();
                for(Account acc : [select id,Pardot_Program_Name__c from account where Pardot_Program_Name__c in : otherProgramsValueSet]){
                    accNamesToIdsMap.put(acc.Pardot_Program_Name__c,acc.Id);
                }
                for(Id accId : accNamesToIdsMap.values()){
        affiliationListToBeInserted.add(new hed__Affiliation__c(hed__Account__c=accId,hed__Contact__c=conInsertList[i].Id));
    }
                }
        }
        }
        }
        insert relation;
        insert affiliation;
        insert affiliationListToBeInserted;
    }
    LeadStatus convertStatus = [Select MasterLabel from LeadStatus where IsConverted = true limit 1];
 
List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
    map<Id,Contact> conMap = new map<Id,Contact>();
for (Lead lead: Trigger.new) {
if (!lead.isConverted && lead.Status == 'New' ) {
Database.LeadConvert lc = new Database.LeadConvert();
String opportunityName = lead.Name;
 
            lc.setLeadId(lead.Id);
            lc.setSendNotificationEmail(false);
            lc.setDoNotCreateOpportunity(true); 
            String currentemail = lead.Email;
            List<Contact> id1 = [SELECT Id, Email,AccountId FROM Contact WHERE Email = :currentemail AND recordtype.name = 'Lead'];
                String Idcon;
                string accname123;
                 for(Contact ce1 : id1){
                          Idcon = ce1.Id;
                          accname123 = ce1.AccountId;
              }
                  lc.setContactId(Idcon);
                  lc.setAccountId(accname123);
                  lc.setConvertedStatus(convertStatus.MasterLabel);
                  leadConverts.add(lc);
            }
            }
                if (!leadConverts.isEmpty()) {
                List<Database.LeadConvertResult> lcr = Database.convertLead(leadConverts);
}
}


 
Karthikeyan Rajendran 14Karthikeyan Rajendran 14
Hi Sainath

      The following lines of code of yours is what causing the issue (List index out of bounds : 3)
               
for(Integer i = 0, s = conInsertList.size(); i < s; i += 2){
       // some lines of code
       hedrel.hed__Contact__c = conInsertList[i + 1].Id;
       //some lines of code
}
 
Lets say the size of conInsertList is 3. After the the loop is executed once the value of variable i will be 2 as the variable in incremented by 2.
and in this statement conInsertList[i + 1].Id you are trying to fetch value from index 3 which is not at all available. As you know the list index starts from 0 and you have value till index 2 (0,1,2)

Not sure of your business requirement to have such statement but this is what is causing the issue.

Regards
Karthik
Sainath VenkatSainath Venkat
Hi Karthikeyan Rajendran 14, thanks for helping me out.

Actually, On lead object I have two sections Student details(Standard lead Fields) and parent details(create custom field like Fname, Lname and Email).

So once Parent_or_guardian__c = true then I need to create two Contacts for student and parent, then I need to catch those two contact ids then create a record in hed_Relationship object where hed__Contact__c = studentcontactId and hed__RelatedContact__c = parent Id so I used for loop.
If lead contains only student section is filled then no need to create relationship record.

Can you please help me out in this issue here if possible.
Ajay K DubediAjay K Dubedi
Hi Sainath,

Line Number 26 to 30 replace by:
 
List<Account> account = new List<Account>();
if(listname.size() > 0) {
    account = [SELECT Id,Name,Pardot_Program_Name__c from Account WHERE Pardot_Program_Name__c IN : listname LIMIT 1];
}
string record;
if(account.size() > 0) {
    for(Account acc : account){
        record = acc.Id; 
    }
}

Line Number 31 to 35 replace by:

List<Contact> cem = new List<Contact>();
if(listEmail.size() > 0) {
    cem = [SELECT Id, Email FROM Contact WHERE Email IN : listEmail LIMIT 1];
}
String cemail;
if(cem.size() > 0) {
    for(Contact ce : cem){
        cemail = ce.Email;
    }
}



You need to add some null check conditions, for this, follow this link and change code according to your requirement:
https://developer.salesforce.com/forums/?id=9062I000000IMGtQAO

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
Sainath VenkatSainath Venkat
Hello Ajay, thanks a lot for your time and replying me.

Even after changing the code as you suggested, I am still getting the same error when I import bulk leads.
"ContactCreationFromLead: execution of BeforeUpdate
caused by: System.ListException: List index out of bounds: 3"

I think this is because of below loop.
for(Integer i = 0, s = conInsertList.size(); i < s; i += 2){        // some lines of code      
hedrel.hed__Contact__c = conInsertList[i + 1].Id;        //some lines of code }
What exactly I am doing is On lead object I have two sections Student details(Standard lead Fields) and parent details(create custom field like Fname, Lname and Email).

So once Parent_or_guardian__c = true then I need to create two Contacts for student and parent, then I need to catch those two contact ids then create a record in hed_Relationship object where hed__Contact__c = studentcontactId and hed__RelatedContact__c = parent Id so I used for loop.
If lead contains only student section is filled then no need to create relationship record.
Karthikeyan Rajendran 14Karthikeyan Rajendran 14
Hi Sainath 
  
      Here is the code to which i created for another question but it looks similar to your requirement of creating two contacts and updating it in another object. Please have a look at it.
//Trigger class

trigger LeadTrigger on Lead (After insert){

  LeadTriggerHandler handler = new LeadTriggerHandler();

  if(Trigger.isAfter && Trigger.isInsert){
      hander.afterInsertProcess(Trigger.New);
  }
}


//Handler class

public class LeadTriggerHandler {

  List<Lead> noParentLeadList = new List<Lead>();
  List<Lead> parentLeadList = new List<Lead>();
  List<Contact> insertConList = new List<Contact>();
  List<RelationShip__c> insertRelationShipList = new List<RelationShip__c>();

  public static void afterInsertProcess(List<Lead> leadList){

    for(Lead leadKey : leadList){

      if(leadKey.Parent__c = false){
         //list which contains Parent__c = false
         noParentLeadList.add(leadKey);
      }else{
         //list which contains Parent__c = true
         parentLeadList.add(leadKey);
      }
    }

    if(noParentLeadList != null && noParentLeadList.size() > 0)
      createContactNoParent(noParentLeadList);

    if(parentLeadList != null && parentLeadList.size() > 0)
        Map<Id,List<Contact>> insertConMap = createContactParent(parentLeadList);

    //contact insert operation
    for(Id idk : insertConMap.keySet()){

      insertConList.addAll(insertConMap.get(idk));
    }
    insert insertConList;

    //setting up inserted contact's Id in RelationShip__c object.
    for(Id IdKey : insertConMap.keySet()){

        RelationShip__c rel = new RelationShip__c(
          rel.Contact1__c = insertConMap.get(IdKey).get(0).Id,
          rel.Contact2__c = insertConMap.get(IdKey).get(1).Id,
        );
        insertRelationShipList.add(rel);
    }

    insert insertRelationShipList;
}

  public static Map<Id,List<Contact>> createContactParent(List<Lead> incomingLeadList){

  Map<Id, List<Contact>> contactMap = new Map<Id,List<Contact>>();
  for(Lead ldKey : incomingLeadList){

      for(Integer i =0 ;i<2; i++){
        List<Contact> conList = new List<Contact>();
        Contact con = new Contact(
           con.LastName = ldKey.LastName,
           con.FirstName = ldKey.FirstName,
        );
        conList.add(con);
        contactMap.put(IdKey, conList);
      }
    }
  }


  public static void createContactNoParent(List<Lead> incomingLeadList){

  List<Contact> contactList = new List<Contact();
  for(Lead ldKey : incomingLeadList){

    Contact con = new Contact(
       con.LastName = ldKey.LastName,
       con.FirstName = ldKey.FirstName,
    );
    contactList.add(con);
  }

  insert contactList;

}

Regards
karthik