Skip to content

Instantly share code, notes, and snippets.

@britishboyindc
Created February 16, 2017 01:10
Show Gist options
  • Select an option

  • Save britishboyindc/1e5f29d8cdc8bf3603d655b2b886f723 to your computer and use it in GitHub Desktop.

Select an option

Save britishboyindc/1e5f29d8cdc8bf3603d655b2b886f723 to your computer and use it in GitHub Desktop.
trigger Employee_Demo on Employee__c (after insert, after update) {
//Create a map of the leaves for each Gender/Status Combo. Consider a setting for this
Map<String, List<String> > LeaveTypeMap = new Map<String, List<String> > ();
LeaveTypeMap.put('Female:Full Time', new List<String>{'Maternity Leave','Annual Leave','Personal Leave','Unpaid Leave'});
LeaveTypeMap.put('Male:Full Time', new List<String>{'Paternity Leave','Annual Leave','Personal Leave','Unpaid Leave'});
LeaveTypeMap.put('Female:Part Time', new List<String>{'Unpaid Leave'});
LeaveTypeMap.put('Male:Part Time', new List<String>{'Unpaid Leave'});
//Create list to hold new leave records
List<Leave__c> LeavestoCreate = new List<Leave__c> ();
//Is this an insert? If so, just create records
if (Trigger.IsInsert) {
for(Employee__c l : trigger.new){
String sEmpType = l.Gender__c + ':' + l.Status__c;
for (String type : LeaveTypeMap.get(sEmpType)) {
Leave__c Child = new Leave__c();
//create the Child record as in your example, with this extra bit for the male/female case
Child.Leave_Type__c = type;
Child.Employee__c = l.Id;
LeavestoCreate.add(Child);
}
}
insert LeavestoCreate;
}
//If update, and it is the status changing delete and recreate perhaps?
if (Trigger.IsUpdate) {
//Did Status change? First build list of changes
List<Employee__c> EmployeesToUpdate = new List<Employee__c>();
for(Employee__c l : trigger.new){
//use the Trigger old map collection to see what value was before the user made the change
if (l.Status__c <> trigger.oldmap.get(l.Id).Status__c) {
EmployeesToUpdate.add(l);
}
}
//Query for leaves that are no longer valid so we can delete them
List<Leave__c> LeavestoDelete = [Select Id FROM Leave__c WHERE Employee__c IN :EmployeesToUpdate];
//Now create new ones - but only loop through employees who have changed status
for(Employee__c l : EmployeesToUpdate){
//We could move this code to a class and then re-use code, but for demo purposes we'll just repeat
String sEmpType = l.Gender__c + ':' + l.Status__c;
for (String type : LeaveTypeMap.get(sEmpType)) {
Leave__c Child = new Leave__c();
//create the Child record as in your example, with this extra bit for the male/female case
Child.Leave_Type__c = type;
Child.Employee__c = l.Id;
LeavestoCreate.add(Child);
}
}
//Finally create new records
insert LeavestoCreate;
//Delete old ones
delete LeavestoDelete;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment