You need to sign in to do that
Don't have an account?
Alex 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?
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()); } } }
Use below code for apex trigger.
Let me know the outcomes.
Thanks,
AMit