Adjust Left Employee Count on Undelete

When an Employee record is undeleted, this trigger decreases the “Left Employee Count” on the related Account, maintaining accurate employee metrics.

Learn more with this YouTube playlist.

Solution:

trigger EmployeeTrigger on Employee__c (After undelete) {
        if(Trigger.isUnDelete){
                   if(Trigger.isAfter){
        EmployeeTriggerHandler.updateLeftEmpCountUndeletedOnes(Trigger.New);
                    }
        }
}
public class EmployeeTriggerHandler{
     public static void updateLeftEmpCountUndeletedOnes(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<Id,Account>([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,accIdToAccMap.get(emp.Account__c).L
eft_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;
                 }
       }
}

Want to Apply As Content Writer?

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart

Let's get you started!

Interested in writing Salesforce Content?

Fill in this form and we will get in touch with you :)