Hi, I am writing a trigger that checks a checkbox field in the contact object after calculating the primaryContact, The primaryContact is the contact who has the most commissions, there is one primary contact per account. My code is able to chose a primary contact but it doesnt seem to update the value of the checkbox to true? This is what I have so far:
trigger primaryContact on Commision__c (after insert, after update) {
List<Account> accToCon = [SELECT Id,
(SELECT Id, Name, Total_Commission__c FROM Contacts) FROM Account];
for(Commision__c com : Trigger.New){
for(Account c: accToCon){
Contact primaryContact;
if(!c.Contacts.isEmpty()){
primaryContact = findMaxCommission(c.Contacts);
System.debug(primaryContact);
togglePrimaryContact(c.Contacts, primaryContact.id);
}
else{
continue;
}
}
}
Contact findMaxCommission(List<Contact> contacts){
Contact chosenContact = contacts[0];
Decimal max = contacts[0].Total_Commission__c;
for (Contact i : contacts) {
if (max < i.Total_Commission__c) {
max = i.Total_Commission__c;
chosenContact = i;
}
}
return chosenContact;
}
void togglePrimaryContact(List<Contact> contacts, id primaryContactId){
for(Contact i : contacts){
if(i.id == primaryContactId){
i.Primary__c = true;
}
i.Primary__c = false;
}
}
}
any help would be greatly appreciated! thanks
Oh, sorry, I see I forgot to actually swap the "Primary Contact" flag. :)