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
Jayati AroraJayati Arora 

Hi When I insert same company name using data loader, trigger fails. Please help me with work around

trigger LeadInsert on Lead (after insert) {
map<String,Account> accmap = new map<String,Account>();
list<Account> acclist = new list<Account>();
list<Contact> conlist =new list<Contact>();
list<Opportunity> Opplist = new list<Opportunity>();
for(Lead l:Trigger.new){
  Account acc = new Account ();
  acc.name = l.company;
  accmap.put(acc.name,acc);
}
insert accmap.values();
for(Lead l:Trigger.new){
  Contact con = new Contact();
  con.lastname =l.lastname ;
  con.AccountId= accmap.get(l.company).Id;
  conlist.add(con);
  Opportunity Opp=new Opportunity();
  Opp.AccountId = accmap.get(l.company).Id;
  Opp.Name = 'Opp' + l.lastname;
  Opp.StageName='Closed Won';
  Opp.CloseDate = System.Today();
  Opplist.add(Opp);
}
insert conlist;
insert Opplist;
}
Hargobind_SinghHargobind_Singh
Jayati, 

Are you trying to create a new account, contact and opportunity for every lead ? Are you trying to do some duplicate check for accountname as well ?

What is the error ? 

Jayati AroraJayati Arora

Hargobind,

Yes I wanted to created new account, contact and opportunity on lead insert. There is no error on this trigger. It is working fine but when I try to bulk insert new insert (let say 10 leads) with same company name then this trigger fails.

Vatsal KothariVatsal Kothari
Hi Jayati,

You have created Map i.e accmap.put(acc.name,acc); which stores acc.name in the map key which is the name of the company,
Map keys are always unique so it will overwrite the previous value with new value of account.

If this solves your problem, kindly mark it as the best answer.

Thanks,
Vatsal
Hargobind_SinghHargobind_Singh
Hi Jayati, 

Your triger should work for 10 leads, and should insert 1 account, and 10 contacts under it. Can you tell me what error message are you getting ? Can you post your test class that you are using to bulk-test this trigger ? 



yvk431yvk431
As Vatsal mentioned there is a chance of overriding the Accounts to be inserted, but the code should still work. Can you post the error you are getting, are you sure the error is related to the Lead trigger code ?


--yvk