Skip to main content

and trigger is;trigger DeleteEmployeeCount on Employee__c ( before delete, after delete) {

 if(Trigger.isBefore && Trigger.isDelete ){

     EmployeeTriggerHandler.EmloyeesStatus(Trigger.old);

  }

    else if(Trigger.isAfter && Trigger.isDelete ){

        EmployeeTriggerHandler.updateLeftEmpCountOnAcc(Trigger.old);

    }

 

}

Handler class

public class EmployeeTriggerHandler {

  

    public static void EmloyeesStatus(List<Employee__c> empOld){

        for(Employee__c emp : empOld){

            if(emp.Active__c == true){

                emp.addError('Active Employee cannot be removed');

            }

        }

    }

    

    public static void updateLeftEmpCountOnAcc(List<Employee__c> oldlist){

        Set<id> accIds = new Set<id>();

        List<Account> accToBeUpdated = new List<Account>();

        List<Employee__c> emplist = new list<Employee__c>();

        Map<id, Account> accMap;

        Map <id, Decimal> updatedMap= new map <Id, Decimal>();

        

        for(Employee__c emp: oldlist){

            if(emp.Account__c != null){

                accIds.add(emp.Account__c);

                emplist.add(emp);

            }

        }

        if(!accIds.isEmpty()){

            accMap = new Map<Id, Account>([Select Id , Left_Employee_Count__c from Account Where Id IN: accIds]);

            System.debug(accMap);

        }

        

        if(!emplist.isEmpty()){

            for(Employee__c emp : emplist){

                if(accMap.containsKey(emp.Account__c)){

                    if(updatedMap.containsKey(emp.Account__c)){

                        Decimal count = updatedMap.get(emp.Account__c) + 1;

                        updatedMap.put(emp.Account__c, count);

                        System.debug('Debug count '+ count);

                        System.debug('emp.Account__c'+ emp.Account__c);

                        System.debug('updatedmap'+ updatedMap);

                    }else{

                        updatedMap.put(emp.Account__c, accMap.get(emp.Account__c).Left_Employee_Count__c + 1);

                    }

                }

            }

        }

        for(Id accid : updatedMap.keySet()){

            Account acc = new Account();

            acc.Id = accid;

            acc.Left_Employee_Count__c = updatedMap.get(accid);

            accToBeUpdated.add(acc);

        }

        

        if(!accToBeUpdated.isEmpty()){

            update accToBeUpdated;

        }

    }

}

2 risposte
0/9000