Skip to content

Instantly share code, notes, and snippets.

@mxalix258
Created June 26, 2013 01:24
Show Gist options
  • Save mxalix258/5864003 to your computer and use it in GitHub Desktop.
Save mxalix258/5864003 to your computer and use it in GitHub Desktop.
For each new leave request, should find the user's manager, and populate the user id into the lookup on the leave request record.
@isTest
private class UpdateLeaveRequestTEST {
static testMethod void validateUpdateLeaveRequest() {
Leave_Request__c LR = new Leave_Request__c();
System.debug('Manager before insert'+ LR.Manager__c);
// Insert Time Sheet
insert LR;
// Retrieve the new time sheet
LR = [SELECT Manager__c FROM Leave_Request__c WHERE Id =:LR.Id];
System.debug('Manager after insert' + LR.Manager__c);
// Test that the trigger correctly updated the manager
System.assertEquals('005U0000000VldF', LR.Manager__c);
}
}
trigger UpdateLeaveRequest on Leave_Request__c (before insert, before update ){
/**
1. For each Leave Request being inserted add User Id value in in Set of User Ids.
2. Fetch all Users whose Id is in the Set.
3. Add these fetched Users in a Map <User Id, User object>
4. For each leave request being inserted get User from the map and update the field values
**/
//holds User Ids
Set<Id> setUserIds = new Set<Id>();
//holds a list of Users
List<User> lstUser = new List<User>();
//holds key value pairs of User Id and User Object
Map<Id, User> mapUserObj = new Map<Id, User>();
//holds User object
User UserObj;
//For each leave request being inserted add User Id value in in Set of User Ids.
for(Leave_Request__c LRObj : Trigger.new){
if(LRObj.OwnerId != null){
setUserIds.add(LRObj.OwnerId);
}
}
//Fetch all Users whose Id is in the Set.
lstUser = [select Id, Name, ManagerId from User where Id in :setUserIds Limit 1000];
if(lstUser.size() == 0){
return;
}
//Add these fetched Users in a Map <User Id, User object>
for(User usrObj : lstUser){
mapUserObj.put(usrObj.Id, usrObj);
}
//for each leave request being inserted get User from the map and update the field values
for(Leave_Request__c LRObj : Trigger.new){
//get User object
if(LRObj.OwnerId != null){
if(mapUserObj.containsKey(LRObj.OwnerId)){
UserObj = mapUserObj.get(LRObj.OwnerId);
//map leave request fields to User fields
LRObj.Manager__c = UserObj.ManagerId;
LRObj.Owner2__c = UserObj.Id;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment