I'm new to Apex and need to assign a User to a Contact via lookup field on the contact record based off of the user with the least amount of assignments and matching endpoints (account name custom user field) as the contact.
I am trying to avoid having a SOQL query inside of a for loop but can't exactly figure out how to do so as the query references a variable inside of the loop.
trigger newCoachAssignment on Contact (before update) {
List<Contact> nc = Trigger.new;
Set<contact> newMemberNames = new Set<contact>();
newMemberNames.addAll(nc);
for (Contact myMember : nc){
Contact oldMember = Trigger.Oldmap.get(myMember.Id);
Id oldMemberHasCoach = oldMember.Assigned_Coach__c ;
IF(oldMemberHasCoach == Null){
//only assigning a coach to members who DIDNT previously have an assigned coach.
IF(myMember.Membership_Status__c == 'Active' //creating if statement for eligible members
&& myMember.Portal_Registration_Date__c != Null
&& myMember.Assigned_Coach__c == Null
&& myMember.Account_Name__c != Null
&& myMember.LM_Available__c) {
string myAcc = myMember.Account_Name__c; //varaible for member's account name.
id myNewCoach; //finding user that has same account assignments as member with the least ammount of assignments.
myNewCoach = [select id from user where isactive = true and Eligible_coach__c = true and Eligible_Endpoints__c includes (:myAcc) order by Current_Assignments__c asc limit 1].id;
myMember.Assigned_Coach__c = myNewCoach; //assigning the member a coach.
}
}
}
}