+ Start a Discussion
bujjibujji 

How to add accountId to the List of Contacts

Hi Guys,

I have list of Contacts, i need to add accountId to these contacts and then insert. How we can do it.

I tried the below way but getting some error.

Account account = new Account([select Id from Account Limit 1]);

List<Contact> cons = new List<Contacts>();

for(List<Contact> c:cons){
      c.add(account.Id);
  }
  insert cons;

Thanks,
Bujji
Richard BlakeRichard Blake
Account account = new Account([select Id from Account Limit 1]);

List<Contact> cons = new List<Contacts>();

for(Contact c:cons){
      c.AccountId = account.Id;
  }
  insert cons;
AshlekhAshlekh
Hi,

Account acc ;
for(Account a: [select Id from Account Limit 1])
acc =a;

List<Contact> cons = new List<Contacts>();
//But you don't have any contact to iterate.
if(acc !=null &&  cons != null && cons.size()>0)
{
 for(Contact c:cons){ 
       c.account.Id = acc.id;
   }
  insert cons;
}

IF it helps you than please mark it as a solution and ENJOY APEX
Richard BlakeRichard Blake
c.account.Id will cause an exception. you must use c.accountId