+ Start a Discussion
vineet kumarvineet kumar 

Create list of parent and child records

Hi All,

I need help in below scenario.
I want to create list of Account (parent) first and then list of child contacts in Apex;

e.g.
I have Account A,B,C
Account  A has contactC1
Account B has contact C2
Account C has contact C3

now

first create Account and then Contact. 
I do not have any external id

so I want to kow that how we can achieve it in apex
Thanks
AnkaiahAnkaiah (Salesforce Developers) 
Hi Vineeth,

Try with below trigger code on Account
trigger ContactCreation on Account (After insert) {

    List <Contact> Contactlist = new List<Contact>();
    set<id> accids = new set<id>();    
    if(trigger.Isinsert)
    {
    for(Account acc : trigger.new){

            accids.add(acc.id);
        }   
      
    }
    // you can add list of fields in the below query from Account you would require
   list <Account> Accountlist = [select id, name,phone from Account where id IN:accids];    
    if(Accountlist.size()>0) 
    {
    for(Account accl:Accountlist ){       
        Contact con = new Contact();
        //add list of fields you would require for Contact creation 
        con.LastName = accl.name;
        con.AccountId = accl.id;
		con.FirstName = 'test';
		con.phone = accl.phone;
        Contactlist.add(con);   
      }  
    }
    if (Contactlist.size()>0){  
        insert Contactlist;
    }
}

If this helps, please mark it as best answer.
ravi soniravi soni
hi vineet,
I am considering that you have a trigger on account object  and then you are going to insert contact then follow below trigger.
trigger ContactCreation on Account (After insert) {

    List <Contact> lstContact = new List<Contact>();
    set<string> accids = new set<string>();    
    if(trigger.isAfter && trigger.isinsert){
    for(Account acc : trigger.new){

            accids.add(acc.id);
        }   
      
    }
   
 	
    for(Account existAcc:[select id, name,phone from Account where id In :accids] ){       
        Contact con = new Contact();
        //add list of fields you would require for Contact creation 
        con.FirstName = 'Contact-';       
	    con.LastName = existAcc.name;
        con.AccountId = existAcc.id;
		con.FirstName = 'test';
		lstContact.add(con);   
      }  
   
    if (lstContact.size()>0){  
        insert lstContact;
    }
}


try above trigger and it wll work as your expectation.
don't forget to mark it as best answer if it help you.
Thank you