Track Present Employee Count on Events

This trigger updates the “Present Employee Count” on the related Account whenever Employee records are inserted, deleted, or undeleted.

Explore related triggers here: YouTube playlist.

Solution:

//Same code will work for insert, delete and undelete trigger EmployeeTrigger
on Employee__c(after insert,after delete,after undelete) { if(Trigger.isInsert){ if(Trigger.isAfter){
                                                          EmployeeTriggerHandler.updatePresentEmpCount(Trigger.New);
                       }
        }
        if(Trigger.isDelete){ if(Trigger.isAfter){
                                                          EmployeeTriggerHandler.updatePresentEmpCount(Trigger.New);
                      }
      }
         if(Trigger.isUnDelete){ if(Trigger.isAfter){
                                                           EmployeeTriggerHandler.updatePresentEmpCount(Trigger.New);
                       }
        }
}
public class EmployeeTriggerHandler{


public static void updatePresentEmpCount(List<Employee_c> empList){
    List<Account> accList= new List<Account>(); Set<Id> idSet= new
    Set<Id>();
    for(Employee__c emp:empList){ if(emp.Account__c!=null){
    idSet.add(emp.Account__c);
                   }
   }
   for(Account acc:[SELECT Id, Name,(SELECT Id FROM Employees__r)
                   FROM Account WHERE Id IN:idSet]){
                   acc.Present_Employee_Count__c=acc.Employees__r.size();
                   accList.add(acc);
}
if(!accList.isEmpty()){ update accList;
}
}

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 :)