he UpdateContactCountOnAccount trigger ensures that the custom field Number_Of_Child_Contacts__c on the parent Account is updated with the correct count of associated Contacts. It runs after insert, after update, after delete, and after undelete on the Contact object. The trigger collects Account IDs for Contacts being processed, queries all related Contacts, manually counts them, and updates the custom field on the corresponding Accounts.
trigger UpdateContactCountOnAccount on Contact (after insert, after update, after delete, after undelete) {
Set<Id> accountIdsToUpdate = new Set<Id>();
if (Trigger.isInsert || Trigger.isUndelete) {
for (Contact c : Trigger.new) {
accountIdsToUpdate.add(c.AccountId);
}
} else if (Trigger.isUpdate) {
for (Contact c : Trigger.new) {
accountIdsToUpdate.add(c.AccountId);
}
for (Contact c : Trigger.old) {
accountIdsToUpdate.add(c.AccountId);
}
} else if (Trigger.isDelete) {
for (Contact c : Trigger.old) {
accountIdsToUpdate.add(c.AccountId);
}
}
// Map to hold accountId and corresponding contact count
Map<Id, Integer> accountContactCountMap = new Map<Id, Integer>();
// Initialize the map with account IDs
for (Id accountId : accountIdsToUpdate) {
accountContactCountMap.put(accountId, 0);
}
// Query all contacts for the accounts to be updated
List<Contact> contacts = [
SELECT AccountId
FROM Contact
WHERE AccountId IN :accountIdsToUpdate
];
// Count the number of contacts for each account
for (Contact contact : contacts) {
if (accountContactCountMap.containsKey(contact.AccountId)) {
accountContactCountMap.put(contact.AccountId, accountContactCountMap.get(contact.AccountId) + 1);
} else {
accountContactCountMap.put(contact.AccountId, 1);
}
}
// Prepare the list of accounts to be updated
List<Account> accountsToUpdate = new List<Account>();
for (Id accountId : accountContactCountMap.keySet()) {
accountsToUpdate.add(new Account(Id = accountId, Number_Of_Child_Contacts__c = accountContactCountMap.get(accountId)));
}
// Update the accounts
if (!accountsToUpdate.isEmpty()) {
update accountsToUpdate;
}
}
No comments:
Post a Comment