You need to sign in to do that
Don't have an account?
Andréa de Faria
After Update in Apex Class
I added the Apex Class and Apex trigger below to update the field Number_of_Contacts at the Account level when a Contact is added or removed to a certain Account:
Class:
Thank you,
Class:
public without sharing class ContactTriggerHandler { private Set<Id> getAccountIds(List<Contact> contacts) { Set<Id> accountIds = new Set<Id>(); for(Contact c : contacts) { if(c.AccountId != null) { accountIds.add(c.AccountId); } } return accountIds; } private Map<Id, Account> getAccountMap(Set<Id> accountIds) { return new Map<Id, Account>([SELECT Id, Number_of_Contacts__c FROM Account WHERE Id in :accountIds]); } public void process(List<Contact> contacts, System.TriggerOperation operation) { Set<Id> accountIds = getAccountIds(contacts); if(accountIds.size() > 0) { Map<Id, Account> accountMap = getAccountMap(accountIds); for(Contact c : contacts) { if(accountMap.containsKey(c.AccountId)) { switch on operation{ when AFTER_INSERT { accountMap.get(c.AccountId).Number_of_Contacts__c += 1; } when AFTER_DELETE { accountMap.get(c.AccountId).Number_of_Contacts__c -= 1; } when AFTER_UNDELETE { accountMap.get(c.AccountId).Number_of_Contacts__c += 1; } when AFTER_U { accountMap.get(c.AccountId).Number_of_Contacts__c += 1; } } } } update accountMap.values(); } } }Trigger:
trigger ContactTrigger on Contact (after insert, after delete, after undelete) { ContactTriggerHandler handler = new ContactTriggerHandler(); switch on Trigger.operationType { when AFTER_INSERT { handler.process(Trigger.new, Trigger.operationType); } when AFTER_DELETE { handler.process(Trigger.old, Trigger.operationType); } when AFTER_UNDELETE { handler.process(Trigger.new, Trigger.operationType); } } }However, how can I include a line of code that updates the Number_of_Contacs__c field when a Contact moves to a different Account?
Thank you,
Did you try including afterupdate context as well in the same trigger.Please checj the below stack exchange question which shows the similar implementation.
https://salesforce.stackexchange.com/questions/138455/count-the-contacts-in-the-related-list-of-account-and-display-the-contact-count
Let me know if you face any issues.
If this solution helps, Please mark it as best answer.
Thanks,