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
snehil kumarsnehil kumar 

Exception in trigger, fail to update the field on account which is used to count the number of contact with specific type

Hi all,
Please help me out.
I posted my trigger please it throws the exception 


Exception Details: Update failed. First exception on row 0 with id 0035000003IGI8AAAX; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ContactTrainerCountTrigger: execution of AfterUpdate

caused by: System.QueryException: Record Currently Unavailable: The record you are attempting to edit, or one of its related records, is currently being modified by another user. Please try again.

My trigger named "ConactTrainerCountTrigger" and the trigger code is given below:
trigger ContactTrainerCountTrigger on Contact (After insert, After delete, After undelete, After Update) {
    Set<Id> parentIdsSet = new Set<Id>();
    List<Account> accountListToUpdate = new List<Account>();
    IF(Trigger.IsAfter){
        IF(Trigger.IsInsert || Trigger.IsUndelete){
            FOR(Contact c : Trigger.new){
                if(c.AccountId!=null){   
                    parentIdsSet.add(c.AccountId);
                    
                }
            }
            System.debug('parentIdsSet' + parentIdsSet);
        }
        IF(Trigger.IsUpdate){
            FOR(Contact c : Trigger.new){
                if(c.AccountId!=null){
                    if(Trigger.oldMap.get(c.Id).Type__c != c.Type__c || Trigger.oldMap.get(c.Id).AccountId != c.AccountId){
                        parentIdsSet.add(Trigger.oldMap.get(c.Id).AccountId);
                        parentIdsSet.add(c.AccountId);
                    }
                }
            }
        }
        IF(Trigger.IsDelete){
            FOR(Contact c : Trigger.Old){
                if(c.AccountId!=null){   
                    parentIdsSet.add(c.AccountId); 
                }
            }
        }
        
          
        List<Account> accountList = new List<Account>([Select id ,Name,Trainer_Count__c, (Select id, Name From Contacts where Type__c = 'Trainer') from Account Where id in:parentIdsSet for Update]);
        System.debug('accountList' + accountList);
        FOR(Account acc : accountList){
            System.debug('acc' +acc);
            List<Contact> contactList = acc.Contacts;
            acc.Trainer_Count__c = contactList.size();
            accountListToUpdate.add(acc);
        }
        update accountListToUpdate;
 
    }
    
}

aNsagaNsag
One small question is there any trigger, process builder or workflow written on Account that's updating contact again. I would advise do close all trigger workflow rule and process builder on the account and contact both and execute this trigger hopefully some other piece of code is a trigger because of this code.