1

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;
}
}
  • 1
    What exactly are you hoping to accomplish with this trigger? It's hard to know what changes to suggest without understanding your high level objective. – Adrian Larson Apr 21 '17 at 20:03
  • 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. – Harv Apr 21 '17 at 20:39
4

Users don't have owners. You probably meant something like:

for(Integer index = 0, size = Trigger.new.size(); index < size; index++) {
  if(Trigger.isInsert || Trigger.old[index].OwnerId != Trigger.new[index].OwnerId) {
    // New record or owner changed ...

As far as the rest of your code, some pointers:

  • New records have no children

There's no point in using after insert, because there will never be any contacts to query.

  • No need to guard against empty lists before loops or DML

You're allowed to iterate over empty lists, so there's no real need to see if there's any contacts in the list before looping over them, or before running the DML.

  • Check the fields you query

c.account.ownerid hasn't been queried and will result in an error. Make sure you query the field.

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.