You need to sign in to do that
Don't have an account?
Alex Campbell 18
Trigger code efficiently to avoid: "Apex CPU time limit exceeded"
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?
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()); } }
Try to add RecordtypeID check when you are looping through contacts.
if (c.AccountId != null && recordtypeid='Something') { acctIds.add(c.AccountId); }
You can also include the RecordtypeID in the SOQL.
Please mark it as best answer if it is helpful.
When I go to Setup > Customize > Contacts > Record Types there are none so I cannot add RecordtypeID to the loop.
Do you have any other suggestions?