When an Employee record is deleted, this trigger updates the “Left Employee Count” field on the related Account, keeping employee metrics accurate.
Explore similar triggers here: YouTube playlist.
Solution:
trigger EmployeeTrigger on Employee__c (After delete)
{ if(Trigger.isDelete){ if(Trigger.isAfter){
EmployeeTriggerHandler.leftEmpCount(Trigger.old);
}
}
}
public class EmployeeTriggerHandler{
public static void leftEmpCount(List oldEmpList){
Set<Id> accIds=new Set<Id>();
List<Account> accToBeUpdated=new List<Account>();
Map<Id,,Account> accIdToAccMap;
List<Employee_c> empList= new List<Employee_c>();
Map<Id,Decimal> accIdToTotalCount= new Map<Id,Decimal>();
for(Employee__c emp:oldEmpList){
if(emp.Account__c!=null){
accIds.add(emp.Account__c); empList.add(emp);
}
}
if(!accIds.isEmpty()){
accIdToAccMap= new Map([SELECT
Id,Left_Employee_Count__c FROM Account WHERE Id
IN:accIds]);
}
if(!empList.isEmpty()){ for(Employee__c emp:empList){
if(accIdToAccMap.containsKey(emp.Account__c)){
if(accIdToTotalCount.containsKey(emp.Account__c)){ Decimal
count =
accIdToTotalCount.get(emp.Account__c)+1;
accIdToTotalCount.put(emp.Account__c,count);
}else{ accIdToTotalCount.put(emp.Account__c,accIdToAcc
Map.get(emp.Account__c).Left_Employee_Count__c+1);
}
}
}
}
for(Id accId:accIdToTotalCount.keySet()){ Account acc= new Account();acc.Id=accId;
acc.Left_Employee_Count__c=accIdToTotalCount.get(accId);
accToBeUpdated.add(acc);
}
if(!accToBeUpdated.isEmpty()){ update
accToBeUpdated;
}
}
}