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
Alex Campbell 18Alex Campbell 18 

Spot the Trigger Mistake

Hi all,

I have written a trigger to count the number of active contacts (User_suspended__c) on an active account (Active__c). When I test the trigger in sandbox by adding contacts to an active account, it populates the the aggregate field (active_users__c) correctly. However, when I change all the contacts to inactive it still shows a count of 1. For exampe, if an account has three active contacts active_users__c = 3 but when I suspend them all contacts active_users__c = 1. 

Why is my trigger not updating the account when all contacts on the account are not active? Where am I making the mistake?
trigger sum_active_users on Contact (after delete, after insert, after undelete, 
after update) {

Set<Id> cons = trigger.isDelete ? Trigger.oldMap.keyset() : Trigger.newMap.keyset();

// Create a list of account ids where a change has happened to a contact on the account
Set<Id> acctIds = new Map<Id, Account>([select Id 

 	                                      from account 

 	                                      where Id in (select AccountId

 	                                                   	 from Contact

 	                                                   	where Id in : cons

 	                                                   	  and AccountId != null)]).keySet();

// Create a list of accounts that will be updated with the number of active contacts related to
// the account
List<Account> acctToUpdate = new List<Account>();

// Use account ids to get the sum of active contacts related to the account
for (AggregateResult ar : [select AccountId,

								  Count(id) ContactCount

                             from Contact

                            where AccountId in : acctIds

                              and Source_of_data__c = 'Site A'

                              and Active__c = 'Yes'

                              and User_suspended__c = 'No - active' 

                          group by AccountId]){


      // Create an account object to be used for the update operation
     Account acc = new Account();

     // Add account id to the account object
     acc.Id = (Id) ar.get('AccountId'); 

     // Add the number of active contacts to the account object
     acc.active_users__c = (Integer)ar.get('ContactCount');

     // Add account object to the accounts list
     acctToUpdate.add(acc);

 }

 	// Check if there are any accounts to be updated
    if (!acctToUpdate.isEmpty()) {

    	// Catch and print errors in any account update 
    	try{

    		// Update accounts
    		update acctToUpdate;

    		}Catch(Exception e){

    			System.debug('Exception :'+e.getMessage());

    		}

    	}

    }

 
Amit Singh 1Amit Singh 1
Alex,

Use below code for apex trigger.
 
trigger ContactTrigger on Contact (after delete, after insert, after undelete, after update) {

    List<Contact> contactList = new List<Contact>();
    contactList = Trigger.isDelete ? Trigger.Old : Trigger.New;
    Set<Id> accountIdSet = new Set<Id>();
    FOr(Contact c : contactList){
       If(c.AccountId!=null){
           accountIdSet.add(c.AccountId);
       }
    }
    
    List<Account> accountList = new List<Account>();
    accountList = [Select Id, Name, Active_Users__c, 
                          (Select Id, Name From Contacts Where Active__c='Yes' 
                                  AND Source_of_data__c = 'Site A' AND User_suspended__c = 'No - active') 
                                      From Account Where Id IN: accountIdSet];
    
    For(Account a : accountList){
        a.Active_Users__c = a.Contacts.size();
    }
    
    try{
        update accountList;
    }catch(Exception e){
        
    }
 
}
Let me know the outcomes.
Thanks,
AMit