function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jon FoyJon Foy 

Need Help writing a Trigger to Populate fields on a Custom Object when saved.

We have a custom object 'TimeSlip' that I need to have a couple fields auto-populated via trigger if they are left blank when a new 'TimeSlip' is saved.  The first is a lookup field to the Contact object.  The second is a lookup field to another custom object.

The two fields I need to auto populate are:
Resource_Name__c - Lookup(Contact) field that, if blank, should auto populate with the current user name {!User.Name} on save.
Case_Resource_ID__c - Lookup(Case Resource) field that, if blank, should auto populate with the Case Resource ID, where {!User.Name} matches the Case Resource Name, on save.

Any help would be greatly appriciated!

 

Best Answer chosen by Jon Foy
Vatsal KothariVatsal Kothari
I hope this will solve your all problem and fullfill your requirement..

trigger updateTimeSlip on TimeSlip__c (before insert,before update){
    Map<Id,Id> caseResourceMap = new Map<Id,Id>();
    String userId = userInfo.getUserId();
    String userName = userInfo.getName();
    Set<Id> caseIds = new Set<Id>();
      
    for(TimeSlip__c ts : trigger.new){
        caseIds.add(ts.Case__c);
    }
    for(Case_Resource__c caseResource : [select id,Case__c from Case_Resource__c where Case_Resource_Name__c =: userId and Case__c IN: caseIds ]){
        caseResourceMap.put(caseResource.Case__c,caseResource.Id);    
    }    
    
    List<Contact> contactList = [select id,Name from Contact where Name =: userName];
    System.debug('contactList '+contactList );
    
    for(TimeSlip__c ts : trigger.new){
        if(ts.Resource_Name__c == null){
            if(contactList[0].Id != null){
                ts.Resource_Name__c = contactList[0].Id;
            }
        }
        
        if(ts.Case_Resource_ID__c == null){
            if(caseResourceMap.containsKey(ts.Case__c) && caseResourceMap.get(ts.Case__c) != null){
                ts.Case_Resource_ID__c = caseResourceMap.get(ts.Case__c);
            }
        }
    }
}

If this solves your problem, kindly mark it as the best answer.

Thanks,
Vatsal

All Answers

KaranrajKaranraj
Hi Jon - I'm little confused with your requirement. Resource_Name__c - This field lookup to Contact object so I can able to link only contact records not the User object records. Could please clarfiy on this?
Jon FoyJon Foy
Correct, I want to link the contact record, not the user object record.  However I want the field to auto-populate with the contact record name that matches the current user's username.  Make sense?
Vatsal KothariVatsal Kothari
Hi Jon,
I  have try this:-
trigger updateTimeSlip on TimeSlip__c (before insert,before update){
	Map<Id,Case_Resource__c> caseResorceMap = new Map<Id,Case_Resource__c>();
	String userId = userInfo.getUserId();
	String userName = userInfo.getName();
	Id caseResourceId;
	
	for(Case_Resource__c caseResource : [select id from Case_Resource__c where Case_Resource_Name__c =: userName]){
		if(caseResourceId != null && caseResourceId != ''){
			caseResourceId = caseResource.Id;
		}
	}	
	
	List<Conatct> contactList = [select id,Name from Contact where Name =: userName];
	
	for(TimeSlip__c ts : trigger.new){
		if(ts.Resource_Name__c != null && ts.Resource_Name__c != ''){
			if(userList[0].ContactId != null && userList[0].ContactId != ''){
				ts.Resource_Name__c = contactList[0].Id;
			}
		}
		
		if(ts.Case_Resource_ID__c != null && ts.Case_Resource_ID__c != ''){
			if(caseResourceId != null && caseResourceId != ''){
				ts.Case_Resource_ID__c = caseResourceId;
			}
		}
	}
}

If this solves your problem, kindly mark it as the best answer.
Hit Like, if it saved your work :-)

Thanks,
Vatsal
Jon FoyJon Foy
Getting the following compile error:
Error: Compile Error: Variable does not exist: userList at line 17 column 16
KaranrajKaranraj
Change the line number 17 with below updates

if(ContactList[0].Id != null && ContactList[0].Id != ''){
    ts.Resource_Name__c = contactList[0].Id;
   }


Vatsal KothariVatsal Kothari
trigger updateTimeSlip on TimeSlip__c (before insert,before update){
	Map<Id,Case_Resource__c> caseResorceMap = new Map<Id,Case_Resource__c>();
	String userId = userInfo.getUserId();
	String userName = userInfo.getName();
	Id caseResourceId;
	
	for(Case_Resource__c caseResource : [select id from Case_Resource__c where Case_Resource_Name__c =: userName]){
		if(caseResourceId != null && caseResourceId != ''){
			caseResourceId = caseResource.Id;
		}
	}	
	
	List<Conatct> contactList = [select id,Name from Contact where Name =: userName];
	
	for(TimeSlip__c ts : trigger.new){
		if(ts.Resource_Name__c != null && ts.Resource_Name__c != ''){
			if(contactList[0].ContactId != null && contactList[0].ContactId != ''){
				ts.Resource_Name__c = contactList[0].Id;
			}
		}
		
		if(ts.Case_Resource_ID__c != null && ts.Case_Resource_ID__c != ''){
			if(caseResourceId != null && caseResourceId != ''){
				ts.Case_Resource_ID__c = caseResourceId;
			}
		}
	}
}

Sorry just replace userList with contactList.

Jon FoyJon Foy
Error: Compile Error: Invalid field ContactId for SObject Contact at line 17 column 31
KaranrajKaranraj
Replace contactId into Id in the condition.
Vatsal KothariVatsal Kothari
Sorry Again..
just replace line 17 with below code:

if(ContactList[0].Id != null && ContactList[0].Id != ''){
    ts.Resource_Name__c = contactList[0].Id;
   }


Jon FoyJon Foy
Thanks for your effort.  The apex trigger saved successfully in my sandbox, however when i create a new timeslip...the fields are not being populated.
Vatsal KothariVatsal Kothari
Have you checked that Contact and Case Resource have Record with same username?
Jon FoyJon Foy
yes both match my current username.
Vatsal KothariVatsal Kothari
Do System.debug for caseResourceId & contactList and see if its giving some result or not.
Jon FoyJon Foy
unfortunately i have no idea how to do that.
Jon FoyJon Foy
Can anyone help me understand how to debug?
Vatsal KothariVatsal Kothari
Hey Jon,

Below is the working trigger:-

trigger updateTimeSlip on TimeSlip__c (before insert,before update){
    Map<Id,Case_Resource__c> caseResorceMap = new Map<Id,Case_Resource__c>();
    String userId = userInfo.getUserId();
    String userName = userInfo.getName();
    Id caseResourceId;
    
    for(Case_Resource__c caseResource : [select id from Case_Resource__c where Case_Resource_Name__c =: userId]){
        caseResourceId = caseResource.Id;        
    }   
    System.debug('caseResourceId '+caseResourceId );
	
    List<Contact> contactList = [select id,Name from Contact where Name =: userName];
    System.debug('contactList '+contactList );
	
    for(TimeSlip__c ts : trigger.new){
        if(ts.Resource_Name__c == null){
            if(contactList[0].Id != null){
                ts.Resource_Name__c = contactList[0].Id;
            }
        }
        
        if(ts.Case_Resource_ID__c == null){
            ts.Case_Resource_ID__c = caseResourceId;
        }
    }
}

If this solves your problem, kindly mark it as the best answer.

Thanks you.
Jon FoyJon Foy
This is populating the Case Resource Id now, which is great. However I need it to go one step further.  a user can have a separate case resource id on every case.  So I need it to grab the Cass Resource ID where Case matches the Case on the timeslip.  Is that possible?
Vatsal KothariVatsal Kothari
caseResourceId contains ID of Case Resource Only which is unique for each Case Resource.
Jon FoyJon Foy
Correct, but users can have multiple case resource ID's.   So what's happening is i'm getting a case Resrouce ID for the correct user that pertains to the wrong case.

Can a 2nd condition be added to the following line that makes sure the id selected has a Case__c (on Case Resource Object) that matches the Case__c manually entered on the timeslip before saving?

for(Case_Resource__c caseResource : [select id from Case_Resource__c where Resource_Name__c =: userId]){
Vatsal KothariVatsal Kothari
If user manually selects the Case Resouce Id then Trigger will not update the Case Resource Id,It will update only when user manually didnt select the case.
Jon FoyJon Foy
user doesn't select the case resource id, but they are selecting the case that the timeslip is a child of (master=child relationship).  So I need to auto-populate the Case Resource ID with the ID where Case matches the Case the user has entered on the Timeslip, AND where the Resource Name matches the current username.  The second criteria is there, need the 1st still.
Vatsal KothariVatsal Kothari
User selects the Case thats correct, but internally lookup field displayed by giving ID. So in TimeSlip Case Resource Id displaying name of the Case but basically it is the Id of the Case.
Jon FoyJon Foy
I think we're getting a bit off base here.  My original req. was Case_Resource_ID__c - Lookup(Case Resource) field that, if blank, should auto populate with the Case Resource ID, where {!User.Name} matches the Case Resource Name, on save.

I have sense realized I need to add to that since this will return multiple case resource ID's.  A user can be assigned a case resource id for many cases.  I want to pull back the 1 case resource ID where the username matches the Case Resrouce Name, and the Case on the case resource name, matches the Case on the Timeslip.
Vatsal KothariVatsal Kothari
Case on the case resource name, matches the Case on the Timeslip, But we have two lookup fields one with contact and one with Case Resource.
So with which field of timslip should I match case of case resorce?
Can you give me list of all the fields of both objects?
Jon FoyJon Foy
There is a Case__c field on timeslip, and a Case__c field on Case Resource that i need to match.

Case Resource Fields:
Case__c                             Lookup(Case)
Rate__c                              Formula(Currency)
Resource_Name__c       Lookup(User)

TimeSlip fields:
Case__c                              Master-Detail(Case)
Resource_Name__c        Lookup(Contact)
Case_Resource_ID__c   Lookup(Case Resource)
Vatsal KothariVatsal Kothari
I hope this will solve your all problem and fullfill your requirement..

trigger updateTimeSlip on TimeSlip__c (before insert,before update){
    Map<Id,Id> caseResourceMap = new Map<Id,Id>();
    String userId = userInfo.getUserId();
    String userName = userInfo.getName();
    Set<Id> caseIds = new Set<Id>();
      
    for(TimeSlip__c ts : trigger.new){
        caseIds.add(ts.Case__c);
    }
    for(Case_Resource__c caseResource : [select id,Case__c from Case_Resource__c where Case_Resource_Name__c =: userId and Case__c IN: caseIds ]){
        caseResourceMap.put(caseResource.Case__c,caseResource.Id);    
    }    
    
    List<Contact> contactList = [select id,Name from Contact where Name =: userName];
    System.debug('contactList '+contactList );
    
    for(TimeSlip__c ts : trigger.new){
        if(ts.Resource_Name__c == null){
            if(contactList[0].Id != null){
                ts.Resource_Name__c = contactList[0].Id;
            }
        }
        
        if(ts.Case_Resource_ID__c == null){
            if(caseResourceMap.containsKey(ts.Case__c) && caseResourceMap.get(ts.Case__c) != null){
                ts.Case_Resource_ID__c = caseResourceMap.get(ts.Case__c);
            }
        }
    }
}

If this solves your problem, kindly mark it as the best answer.

Thanks,
Vatsal
This was selected as the best answer
Jon FoyJon Foy
This is awesome! works great, and is inserting the correct case resource ID on save.  Only issue left is, the resource name is still blank.