Apologies in advance as my understanding of Apex is pretty bad... I'm attempting to create a trigger that updates the owners of all Contacts within an Account when a custom user lookup field on the Account is changed. Below is what I've got, but I'm definitely not storing the variables properly...
trigger pipelineRepContactUpdate on Account (after update) {
List<Contact>ContactList = new List<Contact>();
List<Contact>UpdatedContactList = new List<Contact>();
List<Contact>FinalContactList = new List<Contact>();
for(Integer index = 0, size = Trigger.new.size(); index < size; index++) {
if(Trigger.isInsert || (Trigger.old[index].Pipeline_Rep__c != Trigger.new[index].Pipeline_Rep__c && Trigger.new[index].Pipeline_Rep__c != NULL)) {
// New record or pipeline rep changed ...
String pr;
pr = [SELECT Pipeline_Rep__c FROM Account WHERE Id IN :Trigger.new LIMIT 1];
ContactList = [SELECT id, OwnerId, AccountId FROM Contact WHERE AccountId IN :Trigger.new];
}
}
For(Contact c:UpdatedContactList){
c.OwnerId = pr.Pipeline_Rep__c;
FinalContactList.add(c);
}
Update FinalContactList;
}
Any help would be appreciated -- thanks!
DML
insidefor loop
no never!!!if(Trigger.isInsert
this condition outside the for loop, do add this check in the very beginning;