You need to sign in to do that
Don't have an account?
_why the unlucky stiff
Compare changed objects in After Update
Hello, I am fairly new to Apex.I need to create a list of accounts for which it's owner has changed in an after update trigger. Can anyone show a sample code if this is simple enough?
Also, what would you use to compare and filter, Trigger.new & Trigger.old OR Trigger.newMap & Trigger.OldMap? Also, how to then update this back to the account object? The documentation does not have an example on this and reading it further confused me. Am I on the right track? This can't be that difficult, can it?
I took a stab at this below and this completely does not work.
public static void ownrChangeUpdate(List<Account> newAccs, List<Account> oldAccs){ List<Account> changedAccs; List<Account> updateAccs; Set<Id> UserId = new Set<Id>(); for (Integer i = 0; i < newAccs.size(); i++) { if (oldAccs[i].OwnerId != newAccs[i].OwnerId) { changedAccs.add(newAccs[i]); } } for(Account a :changedAccs){ UserId.add(a.OwnerId); } Map<ID,User> Usermap= new Map<ID,User>([SELECT ID, Group__c, Branch__c from User where ID IN :UserId]) ; For(Account Acc :changedAccs) { User thisUser = UserMap.get(Acc.OwnerId); If (thisUser != null) { Acc.Group__c = thisUser.Group__c; Acc.Branch__c = thisUser.Branch__c; updateAccs.add(Acc); } } if(!updateAccs.isEmpty()){ update updateAccs; } }
Hi,
For comparing the old and new values, Maps are always preferred because they are two-dimensional. In case of lists, I will have to iterate both the lists and compare their values while in Maps, I can do that directly by passing the Key (Account Id) in both old and new maps and check if the values have changed.
I haven't modified the whole code, but highlighting that part which will help you compare the values:
Let me know if you have any doubts :)
All Answers
Hi,
For comparing the old and new values, Maps are always preferred because they are two-dimensional. In case of lists, I will have to iterate both the lists and compare their values while in Maps, I can do that directly by passing the Key (Account Id) in both old and new maps and check if the values have changed.
I haven't modified the whole code, but highlighting that part which will help you compare the values:
Let me know if you have any doubts :)
Thank You, good sir. I am grateful.While at it, one more question.
Why does Eclipse not 'autocomplete' after 'Trigger.new.____'. For e.g. I saw some examples that have Trigger.newMap.get(some Id).FieldName - When using eclipse, after the Trigger.newMap.___ it pretty much leaves you on your own...looks like you need to know intuitively what is a valid call after that or not. Why is that? Is there a particular place where all these calls and their valid arguments described? Am I missing something?