I have a need to populate a lookup field on a custom object with a partner user. The only problem is that I need this to be populated with the partner user who is set up as a contact under the account that is related to the custom object through a two lookup relationships.
Here is the structure:
Receiving__c: (Custom Object) I'm trying to populate a "Receiver_Contact__c" field with the partner user. I have a formula that populates the Account ID of the Partner User's Account and that is the "Receiver_Account_Number__c" field.
I basically want run a query and return user's where their "contact.AccountId" value matches "Receiver_Account_Number__c" field on my "Receiving__c" object and then set that User Id to my "Receiver_Contact__c" field on that same object.
My code is below, any help is greatly appreciated, as always!
trigger getReceiverUser on Receiving__c (before insert, before update){
//get the acct Id and store it in a set.
set<Id> acctIdSet = new set<Id>();
for(Receiving__c rec: trigger.new){
if(rec.Receiver_Account_Number__c != null){
acctIdSet.add(rec.Receiver_Account_Number__c);
}
}
//query the user records and get the associated accounts.
map<id, User> usrMap = new map<id, User>([SELECT id, contact.accountid from user where contact.accountid IN: acctIdSet]);
//update the Receiving value based on the account id in the record.
for(Receiving__c rec: trigger.new){
if(usrMap.containsKey(rec.Receiver_Account_Number__c)){
rec.Receiver_Contact__c = usrMap.get(rec.Receiver_Account_Number__c).contact.accountid;
}
}
}