0

I'm updating the cases field values that are associated to an account using after update trigger. But one account is having 366 cases to it in which I'm facing Apex CPU time limit exceeded exception on updating the account record.

How it works is , when I'm updating "Info" field in Account object , the same field which presents in Case called "Acc_Info" field also gets updated.

Here is my trigger handler code and I'm calling this from an after update trigger.

Map <Id,String> acctToAcctInfo = new Map <Id,String> () ;
    Set<Id> acctsWithChangedInfo = new Set<Id> ();

for (Account newAcc : (List<Account>)Trigger.new) {
 if ((newAcc.Info__c!= oldAcc.Info__c)) {
    acctsWithChangedInfo.add(newAcc.Id) ;
    acctToAcctInfo.put(newAcc.Id, newAcc.Info__c) ;
        }
}
Map<Id,Case> cMap = new Map<Id,Case>([SELECT Id,AccountId FROM Case WHERE AccountId IN :acctsWithChangedInfo]);
    for (Case c: cMap.values()) {
    c.Info__c= (acctToAcctInfo.get(c.AccountId);
    }

    update cMap.values();

Since List will take more CPU time , I have done Map based query here. Please help me on how can I optimize this code and make this work as expected

  • 1
    Your query for case for preparing map is still inside a for loop. If you remove it out of loop, then it should not be a problem. Code Indentation is your friend. – Raul Jan 4 '18 at 12:02
  • Sorry My mistake !!!! Actually it wasn't inside the loop. Now I've edited it and updated the correct code. – ram135868 Jan 4 '18 at 12:13
  • Is it possible you have Case triggers running? If so, there may be a good way to bypass those triggers for this Info update. – Jeremy Nottingham Jan 4 '18 at 14:21
0

If the fields are always be the same, make Case.Info__c a formula field that presents the Account.Info__c value.

If you need to keep Case.Info__c modifiable (so cannot use a forumla), then I would guess you are hitting the CPU problem not because of the code you list but because other logic runs when you update the Cases. It is that other code that you probably need to optimise (e.g. make that code only act when the relevant Case fields change not when any Case fields change).

  • It's a Rich Text Area field in account , So I can't create a formula field in case. Now I've overcome it by using @future method. Please tell me if the that is a recommended way to use – ram135868 Jan 4 '18 at 12:54
  • @ram135868 I'd start with the point I made in the second paragraph. But moving to async code is the general solution if the governor limit can't be addressed by design improvements,. Usually done via a batchabe though.. – Keith C Jan 4 '18 at 13:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.