I am writing the trigger which maintains the sequence number in the insertion in various cases. So when I am trying to access this trigger for more than 500 records for multiple accounts it is throwing an error like :--
System.DmlException: Insert failed. First exception on row 600; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ContactTrigger: execution of BeforeInsert caused by: System.DmlException: Update failed. First exception on row 0 with id 0035j00000JIEHbAAP;
public void beforeInsert(List<Contact> newConTrigger){
conAcctsIdSet = new Set<Id>();
for(Contact c : newConTrigger){
System.debug('The c is ' + c);
conAcctsIdSet.add(c.AccountId);
}
if(conAcctsIdSet.size()>0){
conWithAcctsList = [Select Id,(Select Id,AccountId,Sequence_Number__c from Contacts Order By sequence_number__c ASC) from Account where Id IN:conAcctsIdSet];
for(Account accts: conWithAcctsList){
conListOld = new List<Contact>();
con = new List<Contact>();
conList = new List<Contact>();
conMap = new Map<Integer,Contact>();
conList.clear();
for(Contact c : newConTrigger){
if(c.AccountId == accts.id){
con.add(c);
}
}
if(accts.contacts.size()>0){
for(Contact conRec : accts.contacts){
conMap.put((Integer)conRec.Sequence_Number__c,conRec);//fillig the with old values
}
System.debug('the old cons are ' + accts.contacts);
conListOld.addAll(accts.contacts);
System.debug('the conMap is 0'+conMap);
addRecords(con,accts.id);
for(Contact c : conMap.values()){
if(conListOld.contains(c)){
conList.add(c);
}
}
}
else{
System.debug('Elsepart');
addRecords(con,accts.id);
}
if(conList.size()>0){
update conList;
}
}
}
}
public void addRecords(List<Contact> newContacts,Id accId){
for(Contact c : newContacts){
Integer val = (Integer)c.Sequence_Number__c;
System.debug('The new ARe :: ' + newContacts);
if(accId == c.AccountId && conMap.containsKey(val)){
for(Integer i = conMap.size()+1;i>val;i--){
conMap.get(i-1).Sequence_Number__c = i;
conMap.put(i,conMap.get(i-1));
}
conMap.put((Integer)c.Sequence_Number__c,c);
c.Sequence_Number__c = conMap.size()+1;
}
else{
conMap.put((Integer)c.Sequence_Number__c , c);
}
System.debug('The Map is ::' + conMap);
}
}