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
Venkatasainath GadhamsettyVenkatasainath Gadhamsetty 

trigger to create multiple records when check box is checked

Hello everyone,

Can anyone help me out in writing a trigger on lead object.

On lead I have following fields
1)LastName
2)FirstName
3)Parent__c (Checkbox)
4)ParentFirstName__c
5)ParentSecondName__c
6)ParentEmail__c

Once lead is created then I want to create one record in contact if Parent__c = 'False'.
If Parent__c is true then I want to create two records in contact where one is for parent and other is for student(standard lead field belongs to student details).
If Parent__c is true then I need to catch the newly created contact Id's then I need to create a record in Relationship__c object where Contact1__c = ParentContactId and Contact__2=StudentContactId

Can anyone helps me out in writing trigge that is bulkified for multiple insertions lead please
Karthikeyan Rajendran 14Karthikeyan Rajendran 14
Hi Venkatasainath

       here is the code to create records based on your requirement.
 
//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;

}

I hope this solution is helpful for you. If it does please mark it as best answer.

Regards
karthik
Sainath VenkatSainath Venkat
Hello Karthikeyan Rajendran 14,

thanks a lot for helping me out in this issue.

Can you please help me out how can I convert lead here, the moment lead created I will be creating contacts then I want to convert the lead too, after converting I want to merge with the contact that was created in trigger
Venkatasainath GadhamsettyVenkatasainath Gadhamsetty
Hi Hello Karthikeyan Rajendran 14,,

I tried your code but I am getting many errors, I tried to fix them but failed.

User-added image

My Code:
 
public class LeadTriggerHandler {

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

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

    for(Lead leadKey : leadList){

      if(leadKey.Parent_or_guardian__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()){

        hed__Relationship__c rel = new hed__Relationship__c(
          rel.hed__Contact__c = insertConMap.get(IdKey).get(0).Id,
          rel.hed__RelatedContact__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;

}
}

 
Sainath VenkatSainath Venkat
Hi Karthikeyan Rajendran 14,

I did many changes to the  code but on inserting lead record with student details(standard lead fields) and parent__c = true and ParentFname != null, parentLname != null then I am getting the following error

LeadTrigger: execution of AfterInsert caused by: System.ListException: List index out of bounds: 1 Class.LeadTriggerHandler.afterInsertProcess: line 41, column 1 Trigger.LeadTrigger: line 3, column 1

my code is below:
trigger:
trigger LeadTrigger on Lead (After insert){ 
    if(Trigger.isAfter && Trigger.isInsert){ 
        LeadTriggerHandler.afterInsertProcess(Trigger.New); 
    } 
}
class:
 
public class LeadTriggerHandler {

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

    public static void afterInsertProcess(List<Lead> leadList){
        List<hed__Relationship__c> insertRelationShipList = new List<hed__Relationship__c>();
        for(Lead leadKey : leadList){

            if(leadKey.Parent_or_guardian__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)); //line28 
            }
            insert insertConList;

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

                //FRED: Does this actually works? Since the "get" returns a list of contact, I think the syntax should be something like insertConMap.get(IdKey)[0].Id but I could be wrong

                hed__Relationship__c rel = new hed__Relationship__c(
                    hed__Contact__c = insertConMap.get(IdKey).get(0).Id,      
                    hed__RelatedContact__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){


            //FRED QUESTION: If I understand correctly , you're building a Map of contacts by lead ID? Why is the loop set to "2"?
            //Why is the RETURN ContactMap in the loop itself? It means it will always contain only ONE item in it.


            for(Integer i =0 ;i<2; i++){
                List<Contact> conList = new List<Contact>(); //This should probably be outside of the (for integer i=0) loop
                Contact con = new Contact(
                    LastName = ldKey.LastName, //line55
                    FirstName = ldKey.FirstName, //line56
                    Email = ldKey.Email
                );
                conList.add(con);
                contactMap.put(ldKey.id, conList);
                return contactMap;  //this return doesn't make sense to me
            }
        }
        return null;
    }


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

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

            Contact con = new Contact(
                LastName = ldKey.LastName, //line71
                FirstName = ldKey.FirstName,
                Email = ldkey.Email
            );
            contactList.add(con);
        }

        insert contactList;

    }
}


 
Karthikeyan Rajendran 14Karthikeyan Rajendran 14
Hi Venkatasainath Gadhamsetty

       I havent created the fields in my organization so I havent executed the code in my organization. Sorry for the inconvenience. I have corrected the code (your code). please check it.

Note: Looks like the field hed__Contact__c is not available in the Object hed__Relationship__c. 
 
public class LeadTriggerHandler {

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

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

    for(Lead leadKey : leadList){

      if(leadKey.Parent_or_guardian__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()){

        hed__Relationship__c rel = new hed__Relationship__c(
          hed__Contact__c = insertConMap.get(IdKey).get(0).Id,
          hed__RelatedContact__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(
           LastName = ldKey.LastName,
           FirstName = ldKey.FirstName,
        );
        conList.add(con);
        contactMap.put(IdKey, conList);
      }
    }
    return contactMap;
  }


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

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

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

Regards
Karthik
Karthikeyan Rajendran 14Karthikeyan Rajendran 14
Hi Sainath

    To answer your comment in line no 37
    >> //FRED: Does this actually works? Since the "get" returns a list of contact, I think the syntax should be something like
    insertConMap.get(IdKey)[0].Id but I could be wrong 
    A : There is nothing wrong with the Syntax and you can use get. Try it out in execute anonymous

    line no . : 69
    >> //FRED QUESTION: If I understand correctly , you're building a Map of contacts by lead ID? Why is the loop set to "2"?
    //Why is the RETURN ContactMap in the loop itself? It means it will always contain only ONE item in it.
    //This return doesnt make sense to me
    A: In my code I missed ou the return statement and you have added the return wrongly inside the loop. It should be outside the for loop.

Anyway I have corrected the errors in the code try it in your org.

Regards
Karthik
Sainath VenkatSainath Venkat
Hello Karthikeyan Rajendran 14,

Thanks for helping me out here, I am able to modify all the changes and get it worked perfectly.

Actually I am converting lead now which is throwing the following error
LeadTrigger: execution of AfterInsert caused by: System.DmlException: ConvertLead failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, accountId must be specified if contactId is not null: [Id] Class.LeadTriggerHandler.afterInsertProcess: line 84, column 1 Trigger.LeadTrigger: line 3, column 1

I did not specified AccountId in createcontactparent because, I have backend process which will create accountid once contact is inserted, can you help me out in this issue so that I can merge the contacts while converting lead.
 
public class LeadTriggerHandler {

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

public static void afterInsertProcess(List<Lead> leadList){
    List<hed__Relationship__c> insertRelationShipList = new List<hed__Relationship__c>();
    List<hed__Affiliation__c> insertaffiliationList = new List<hed__Affiliation__c>();
    for(Lead leadKey : leadList){

        if(leadKey.Parent_or_guardian__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);
        List<String> acctListName =new List<String>();
        Set<String> otherProgramsValueSet = new Set<String>();
        //contact insert operation
        for(Id idk : insertConMap.keySet()){
            insertConList.addAll(insertConMap.get(idk));
        }
        insert insertConList;
        for(Lead l1:parentLeadList)
        {
            if(l1.What_is_your_primary_program_of_interest__c != null){
            acctListName.add(l1.What_is_your_primary_program_of_interest__c);
            }
            if(l1.Other_Programs_of_Interest__c != null){
            otherProgramsValueSet.addAll(l1.Other_Programs_of_Interest__c.split(';'));
            }
        }

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

            hed__Relationship__c rel = new hed__Relationship__c(
                hed__Contact__c = insertConMap.get(IdKey).get(0).Id,
                hed__RelatedContact__c = insertConMap.get(IdKey).get(1).Id,
                hed__Type__c = 'Parent'
            );
            insertRelationShipList.add(rel);
            if(acctListName != null){
            Map<String,Id> accNamesToIdsMap1 = new Map<String,Id>();
            for(Account acc : [select id,Pardot_Program_Name__c from account where Pardot_Program_Name__c in : acctListName]){
                accNamesToIdsMap1.put(acc.Pardot_Program_Name__c,acc.Id);
            }
                for(Id accId : accNamesToIdsMap1.values()){
                  insertaffiliationList.add(new hed__Affiliation__c(hed__Account__c= accId,
                                                           hed__Contact__c=insertConMap.get(IdKey).get(0).Id,
                                                           hed__Primary__c = true,
                                                           hed__Role__c='Prospect'));
                }
            }
            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()){
                  insertaffiliationList.add(new hed__Affiliation__c(hed__Account__c= accId,
                                                           hed__Contact__c=insertConMap.get(IdKey).get(0).Id,
                                                           hed__Role__c='Prospect'));
                }
            }
            List<Id> LeadIds = new List<Id>();
            Database.LeadConvert Leadconvert = new Database.LeadConvert();
            Leadconvert.setLeadId(IdKey);
            LeadStatus Leads= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
            Leadconvert.setConvertedStatus(Leads.MasterLabel);
            Leadconvert.setAccountId(insertConMap.get(IdKey).get(0).AccountId);
            Leadconvert.setContactId(insertConMap.get(IdKey).get(0).Id);
            Leadconvert.setDoNotCreateOpportunity(TRUE); 
            Database.LeadConvertResult Leadconverts = Database.convertLead(Leadconvert);
            System.assert(Leadconverts.isSuccess());
        }
            
        insert insertRelationShipList;
        insert insertaffiliationList;
    }
}

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

    Map<Id, List<Contact>> contactMap = new Map<Id,List<Contact>>();
    List<Contact> conList=null;

    for(Lead tmpLead : incomingLeadList){
            conList = new List<Contact>();
           Contact con = new Contact(
                LastName = tmpLead.LastName, 
                FirstName = tmpLead.FirstName,
               Email = tmpLead.Email
            );
            conList.add(con);

            con = new Contact(
                LastName = tmpLead.Parent_First_Name__c,
                FirstName = tmpLead.Parent_Last_Name__c,
                Email = tmpLead.Parent_Email__c
            );
            conList.add(con);           
            contactMap.put(tmpLead.id, conList);
       }
       return contactMap;
}


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

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

        Contact con = new Contact(
            LastName = ldKey.LastName,
            FirstName = ldKey.FirstName
        );
        contactList.add(con);
    }
    insert contactList;
    List<String> acctListName2 =new List<String>();
        Set<String> otherProgramsValueSet2 = new Set<String>();
    List<hed__Affiliation__c> insertaffiliationList2 = new List<hed__Affiliation__c>();
            for(Lead l1:noParentLeadList)
        {
            if(l1.What_is_your_primary_program_of_interest__c != null){
            acctListName2.add(l1.What_is_your_primary_program_of_interest__c);
            }
            if(l1.Other_Programs_of_Interest__c != null){
            otherProgramsValueSet2.addAll(l1.Other_Programs_of_Interest__c.split(';'));
            }
        }
    if(acctListName2 != null){
            Map<String,Id> accNamesToIdsMap2 = new Map<String,Id>();
            for(Account acc : [select id,Pardot_Program_Name__c from account where Pardot_Program_Name__c in : acctListName2]){
                accNamesToIdsMap2.put(acc.Pardot_Program_Name__c,acc.Id);
            }
                for(Id accId : accNamesToIdsMap2.values()){
                  insertaffiliationList2.add(new hed__Affiliation__c(hed__Account__c= accId,
                                                           hed__Contact__c=contactList.get(0).Id,
                                                           hed__Primary__c = true,
                                                           hed__Role__c='Prospect'));
                }
            }
            if(otherProgramsValueSet2 != null){
            Map<String,Id> accNamesToIdsMap3 = new Map<String,Id>();
            for(Account acc : [select id,Pardot_Program_Name__c from account where Pardot_Program_Name__c in : otherProgramsValueSet2]){
                accNamesToIdsMap3.put(acc.Pardot_Program_Name__c,acc.Id);
            }
                for(Id accId : accNamesToIdsMap3.values()){
                  insertaffiliationList2.add(new hed__Affiliation__c(hed__Account__c= accId,
                                                           hed__Contact__c=contactList.get(0).Id,
                                                           hed__Role__c='Prospect'));
                }
            }
         insert insertaffiliationList2;
}
}

 
Venkatasainath GadhamsettyVenkatasainath Gadhamsetty
Hello Karthikeyan Rajendran 14,

Actually if parent checkbox is checked then I am creating relationship record and affiliation records, like that if parent checkbox is not checked then only one contact will get created now for that contact its creating affiliation records for only one lead, can you review it once plz.
 
public static void createContactNoParent(List<Lead> incomingLeadList){

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

    Contact con = new Contact(
        LastName = ldKey.LastName,
        FirstName = ldKey.FirstName
    );
    contactList.add(con);
}
insert contactList;
List<String> acctListName2 =new List<String>();
    Set<String> otherProgramsValueSet2 = new Set<String>();
List<hed__Affiliation__c> insertaffiliationList2 = new List<hed__Affiliation__c>();
        for(Lead l1:noParentLeadList)
    {
        if(l1.What_is_your_primary_program_of_interest__c != null){
        acctListName2.add(l1.What_is_your_primary_program_of_interest__c);
        }
        if(l1.Other_Programs_of_Interest__c != null){
        otherProgramsValueSet2.addAll(l1.Other_Programs_of_Interest__c.split(';'));
        }
    }
if(acctListName2 != null){
        Map<String,Id> accNamesToIdsMap2 = new Map<String,Id>();
        for(Account acc : [select id,Pardot_Program_Name__c from account where Pardot_Program_Name__c in : acctListName2]){
            accNamesToIdsMap2.put(acc.Pardot_Program_Name__c,acc.Id);
        }
            for(Id accId : accNamesToIdsMap2.values()){
              insertaffiliationList2.add(new hed__Affiliation__c(hed__Account__c= accId,
                                                       hed__Contact__c=contactList.get(0).Id,
                                                       hed__Primary__c = true,
                                                       hed__Role__c='Prospect'));
            }
        }
        if(otherProgramsValueSet2 != null){
        Map<String,Id> accNamesToIdsMap3 = new Map<String,Id>();
        for(Account acc : [select id,Pardot_Program_Name__c from account where Pardot_Program_Name__c in : otherProgramsValueSet2]){
            accNamesToIdsMap3.put(acc.Pardot_Program_Name__c,acc.Id);
        }
            for(Id accId : accNamesToIdsMap3.values()){
              insertaffiliationList2.add(new hed__Affiliation__c(hed__Account__c= accId,
                                                       hed__Contact__c=contactList.get(0).Id,
                                                       hed__Role__c='Prospect'));
            }
        }
     insert insertaffiliationList2;
 }