I am having trouble comparing old and new values of Account ownerid field. Can someone help me to write down the correct syntax or suggest me where and what am i doing wrong. Below is my code.
I have an apex handler class which updates account owner field on Accounts based on Account Owner check box checked on an object called Territory Mapping. Now I am trying to write a trigger which will update all the contact owners for the list of contacts that are related to accounts when there is a change is Account owner field.
trigger ContactOwnerID on Account (After Insert, After Update) {
List<Account>AccList = new List<Account>();
Map<id,user>OldUserMap = new Map<id,user>();
Map<id,user>NewUserMap = new Map<id,user>();
List<Contact>ConList = new List<Contact>();
List<Contact>UpdatedConList = new List<Contact>();
List<Contact>FinalConList = new List<Contact>();
For(Account A:Trigger.new){
If(A.OwnerId != Null && OldUserMap.get(A.id).OwnerId != NewUserMap.get(A.id).OwnerId){
AccList.add(A);
}
If(!AccList.isEmpty()){
ConList =[Select id, OwnerId, AccountId from Contact where AccountId =: AccList];
}
}
If(!ConList.isEmpty()){
For(Contact c:UpdatedConList){
c.OwnerId = c.account.ownerid;
FinalConList.add(c);
}
}
If(!FinalConList.isEmpty()){
Update FinalConList;
}
}