trigger SetPrimary on Commission__c (after insert, after update, after delete) {
//This gets all the account ids associated with the Commission records
Set<Id> accountIds = new Set<Id>();
for (Commission__c c : Trigger.new) {
accountIds.add(c.Account__c);
}
//This should query the database for all the Contact records related to the accounts with commission records
Map<Id, Contact> contacts = new Map<Id, Contact>([SELECT Id, AccountId, Total_Commission__c FROM Contact WHERE AccountId IN :accountIds]);
// Loops through each Account
for (Id accountId : accountIds) {
// Finds the Contact with the highest Total Commission
Contact primaryContact = null;
for (Contact c : contacts.values()) {
if (c.AccountId == accountId) {
if (primaryContact == null || c.Total_Commission__c > primaryContact.Total_Commission__c) {
primaryContact = c;
}
}
}
// Sets the Primary field to true for the primary Contact and false for all others
for (Contact c : contacts.values()) {
if (c.AccountId == accountId) {
c.Primary__c = (c.Id == primaryContact.Id);
}
}
}
update contacts.values();}
trigger SetPrimary on Commission__c (after insert, after update, after delete) {
//This gets all the account ids associated with the Commission records
Set<Id> accountIds = new Set<Id>();
for (Commission__c c : Trigger.new) {
accountIds.add(c.Account__c);
}
//This should query the database for all the Contact records related to the accounts with commission records
Map<Id, Contact> contacts = new Map<Id, Contact>([SELECT Id, AccountId, Total_Commission__c FROM Contact WHERE AccountId IN :accountIds]);
// Loops through each Account
for (Id accountId : accountIds) {
// Finds the Contact with the highest Total Commission
Contact primaryContact = null;
for (Contact c : contacts.values()) {
if (c.AccountId == accountId) {
if (primaryContact == null || c.Total_Commission__c > primaryContact.Total_Commission__c) {
primaryContact = c;
}
}
}
// Sets the Primary field to true for the primary Contact and false for all others
for (Contact c : contacts.values()) {
if (c.AccountId == accountId) {
c.Primary__c = (c.Id == primaryContact.Id);
}
}
}
update contacts.values();
}
Total_Commission_cTotal_Commission__c
is a field in the ContactContact
object (roll-up summary)