[SalesForce] How to insert object records using list of string

Hi i am tring to insert lead records,tried this code

public static list<string> first = new List<string>();
public static list<string> last = new List<string>();
public static list<string> com = new List<string>();
public static list<lead> lead = new list<lead>();
public static lead l = new lead();
integer i=0;
while(i<3){
l.firstname = first.get(i);
l.lastname = last.get(i);
l.company = com.get(i);
i++;
lead.add(l);
system.debug('lead:'+lead);
}

here i am adding string values to first,last,com by using this string values i need to insert list of lead records.
By using this one record only inserting when i m tring to insert more than one record geting error:

System.ListException: Before Insert or Upsert list must not have two identically equal elements

my Debuglog output shown below:

lead:(Lead:{FirstName=p
, LastName=hari
, Company=bics
})
lead:(Lead:{FirstName=h
, LastName=ravi
, Company=bizimpact
}, Lead:{FirstName=h
, LastName=ravi
, Company=bizimpact
})
lead:(Lead:{FirstName=r
, LastName=sfdc
, Company=acuve
}, Lead:{FirstName=r
, LastName=sfdc
, Company=acuve
}, Lead:{FirstName=r
, LastName=sfdc
, Company=acuve
})

like this first record one time second record 2 times third record 3 times added in lead.can u please help on this

Best Answer

You would have to reinitialise the "l" instance variable inside your loop everytime you insert a new lead record in the list, as the elements are stored by reference.

while(i<3){
l.firstname = first.get(i);
l.lastname = last.get(i);
l.company = com.get(i);
i++;
lead.add(l);
l = new Lead();
system.debug('lead:'+lead);
}
Related Topic