You need to sign in to do that
Don't have an account?
Chad Moutes
Help With Apex Trigger
I have an Apex Trigger that takes the list of Tasks that meet a certain criteria and finds the one with the Max Date and then populates a field on the Account with that date. The trigger works great, but I would like it so that if the list size = 0 then the field will return to null. Currently the previous value will just stay in there. Any help would be greatly appreciated.
trigger LastCompletedCallDate on Task (after insert, after update, before delete) { Set<Id> acc_set = new Set<Id>(); List<Account> acc_list = new List<Account>(); if(trigger.isInsert || trigger.isUpdate){ for(Task T: Trigger.new){ if(String.valueof(T.WhatId).startsWith('001') && T.Status=='Completed' && T.Subject=='Completed Call' ){ acc_set.add(T.WhatId); } } } if(trigger.isDelete){ for(Task T: Trigger.old){ if(String.valueof(T.WhatId).startsWith('001') && T.Status=='Completed' && T.Subject=='Completed Call' ){ acc_set.add(T.WhatId); } } } for(AggregateResult aggregateResult:[SELECT max(Due_Date__c)MaxCDate,WhatId FROM Task WHERE WhatID IN: acc_set AND Status ='Completed' AND Subject ='Completed Call' Group By WhatId]){ acc_list.add(new Account(Id=(id)aggregateResult.get('WhatId'),Last_Completed_Call__c=(date)aggregateResult.get('MaxCDate'))); } try{ for(Account acc: acc_List){ if(acc_list.size()>0) update acc_list; else acc.Last_Completed_Call__c = null; } }Catch(Exception e){ system.debug('Exception ***'+e.getMessage()); } }
In your last for loop just above the try, I'd put in a check there and add *every* account to the acc_list, whether it has a max date or not. So you check for the null within that for loop and then add the account accordingly.
Has a max date: acc_list.add(new Account(Id=(id)aggregateResult.get('WhatId'),Last_Completed_Call__c=(date)aggregateResult.get('MaxCDate')));
Doesn't have a max date: acc_list.add(new Account(Id=(id)aggregateResult.get('WhatId'),Last_Completed_Call__c=null));
Alternatively you could track a separate list of the same triggered accounts. If the acc_list has no values, then loop through the backup account list, set the Last_Completed_Call__c to null, then update the list.
-David