I created a trigger on Lead object which creates two records in Contact at a time. Now I want to catch those newly created two contacts and creates a record in relationship object.
I did completed the trigger but I am getting error on lead object when I save the record. "ContactCreationFromLead: execution of AfterInsert caused by: System.ListException: List index out of bounds: 1 Trigger.ContactCreationFromLead: line 56, column 1"
Can anyone help me out in this issue,my trigger is below.
trigger ContactCreationFromLead on Lead (After insert) {
List<Contact> conInsertList = new List<Contact>();
List<hed__Affiliation__c> affiliation = new List <hed__Affiliation__c>();
List<hed__Relationship__c> relation = new List<hed__Relationship__c>();
List<String> listEmail = new List<String>();
if(trigger.isInsert || trigger.isUpdate){
for (Lead em : Trigger.new) {
if(em.Email != null){
listEmail.add(em.Email);
}
}
}
List<Contact> cem = [SELECT Id, Email FROM Contact WHERE Email = :listEmail];
String cemail;
for(Contact ce : cem){
cemail = ce.Email;
}
for(Lead ld : Trigger.new) {
if (ld.Email != cemail && ld.Parent_or_guardian__c == false) {
Contact cnt = new Contact();
cnt.FirstName = ld.FirstName;
cnt.LastName = ld.LastName;
cnt.Email = ld.Email;
cnt.RecordTypeId = '012P00000005ZDpIAM';
conInsertList.add(cnt);
}
else{
if(ld.Email != cemail && ld.Parent_or_guardian__c == true ){
Contact cnt1 = new Contact();
cnt1.RecordTypeId = '012P00000005ZDuIAM';
cnt1.FirstName = ld.Parent_First_Name__c;
cnt1.LastName = ld.Parent_Last_Name__c;
cnt1.Email = ld.Parent_Email__c;
conInsertList.add(cnt1);
Contact cnt2 = new Contact();
cnt2.RecordTypeId = '012P00000005ZDpIAM';
cnt2.FirstName = ld.FirstName;
cnt2.LastName = ld.LastName;
cnt2.Email = ld.Email;
conInsertList.add(cnt2);
}
}
}
if(conInsertList.size()>0){
INSERT conInsertList;
List<Id> conInsert = new List<Id>();
for(Contact con : conInsertList){
conInsert.add(con.Id);
hed__Relationship__c hedrel = new hed__Relationship__c();
hedrel.hed__Contact__c = conInsert[0];
hedrel.hed__RelatedContact__c = conInsert[1];
hedrel.hed__Type__c = 'Parent';
relation.add(hedrel);
}
insert relation;
}
}