function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Wes Reed 27Wes Reed 27 

Trigger that Auto Updates field on parent when child record is updated

Is there a way to automatically update the Callable_Contacts__c field on the Account object when a related Contact is updated?
trigger CallableContacts on Account (before insert, before update) {
    for(Account acc : {
        //Search for related Contacts
        List<Contact> callableContacts = [SELECT  Id, 
                                            FROM Contact 
                                            WHERE Account.Id = :acc.Id];
        System.debug('Callable contacts found: ' + callableContacts.size());

        //For each contact, check whether the Phone Number field is filled in and increment the callable contacts field on Account
        Integer count = 0; 
        if(!callableContacts.isEmpty()) {
            for(Contact con : callableContacts) {
                if(con.Phone != null) {
                    count = count + 1;
                    acc.Callable_Contacts__c = count;

David Zhu 🔥David Zhu 🔥
This trigger is on Account object. You may need to create a AFTER trigger on Contact object.