• Alex Campbell 18
  • NEWBIE
  • 0 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 1
    Replies
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());

    		}

    	}

    }

 
Hello,

I am new to SF development and have written my first few triggers. For the trigger below, I keep running into the error message "Apex CPU time limit exceeded" on production. The trigger is counting the number of contacts, that meet a set of criteria, on an account that are active and use the mobile app.

I have removed nested loops and attemped to do the majority of the work on the DB side but I still receive the same error. Does anoyone have any suggestions on how I can improve the effiency of this code and decrease CPU time? In particular, any suggestions for the first for loops?
trigger sum_active_mobile_users on Contact (after delete, after insert, after undelete, 
after update) {

    // Trigger to calculate the number of active mobile users on an account 

    List<Contact> contacts = Trigger.isDelete ? Trigger.old : Trigger.new;

    Set<ID> acctIds = new Set<ID>();
    
    for (Contact c : contacts) {

         if (c.AccountId != null) {

            acctIds.add(c.AccountId);
        }

    }
    
    List<Account> acctsToRollup = new List<Account>();

      for (AggregateResult ar : [select AccountId AcctId, 

                                        Count(id) ContactCount

                                   from Contact

                                  where AccountId in: acctIds

                                    and Source_of_data__c = 'Sync from site A'

                                    and Active__c = 'Yes'

                                    and User_suspended__c = 'No - active' 

                                    and Date_Of_Mobile_Use__c != null

                               group by AccountId]){

          Account a = new Account();

          a.Id = (Id) ar.get('AcctId'); 

          a.active_mobile_users__c = (Integer) ar.get('ContactCount');

          acctsToRollup.add(a);

      }

    try{

       update acctsToRollup;

    }Catch(Exception e){

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

    }

}

 
Hello,

I am new to SF development and have written my first few triggers. For the trigger below, I keep running into the error message "Apex CPU time limit exceeded" on production. The trigger is counting the number of contacts, that meet a set of criteria, on an account that are active and use the mobile app.

I have removed nested loops and attemped to do the majority of the work on the DB side but I still receive the same error. Does anoyone have any suggestions on how I can improve the effiency of this code and decrease CPU time? In particular, any suggestions for the first for loops?
trigger sum_active_mobile_users on Contact (after delete, after insert, after undelete, 
after update) {

    // Trigger to calculate the number of active mobile users on an account 

    List<Contact> contacts = Trigger.isDelete ? Trigger.old : Trigger.new;

    Set<ID> acctIds = new Set<ID>();
    
    for (Contact c : contacts) {

         if (c.AccountId != null) {

            acctIds.add(c.AccountId);
        }

    }
    
    List<Account> acctsToRollup = new List<Account>();

      for (AggregateResult ar : [select AccountId AcctId, 

                                        Count(id) ContactCount

                                   from Contact

                                  where AccountId in: acctIds

                                    and Source_of_data__c = 'Sync from site A'

                                    and Active__c = 'Yes'

                                    and User_suspended__c = 'No - active' 

                                    and Date_Of_Mobile_Use__c != null

                               group by AccountId]){

          Account a = new Account();

          a.Id = (Id) ar.get('AcctId'); 

          a.active_mobile_users__c = (Integer) ar.get('ContactCount');

          acctsToRollup.add(a);

      }

    try{

       update acctsToRollup;

    }Catch(Exception e){

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

    }

}