I have a requirement When an account is created or edited, the value entered in coverage lead field (which is a lookup to user) should copy over to account owner field and also to the owner field of all related contacts. If the coverage lead field is left blank, last modified by field should copy over to account owner as well as related contact's owner fields. I've built a trigger for this requirement but when I try to update/insert Account the User in lookup field is not populating as owner. Can someone help me what needs to be changed in my trigger.
trigger AccountOwnerUpdate on Account (before insert, before update, after insert, after update) {
Set<Id> accIds = new Set<Id>();
//List<Account> updatedAccList = new List<Account>();
List<Account> updatedConList = new List<Account>();
List<Account> accList = new List<Account>();
if(trigger.isInsert) {
system.debug('bbbbbbb');
for(Account acc : trigger.new) {
accIds.add(acc.Id);
system.debug('entered here');
}
}
if(trigger.isUpdate) {
system.debug('asssss');
for(Account acc : trigger.old) {
accIds.add(acc.Id);
system.debug('entered here');
}
}
for(Account accs : [SELECT Id, Coverage_Lead__c, Owner.Id, LastModifiedById,(SELECT Id, Owner.Id FROM Contacts) FROM Account WHERE Id IN:accIds]) {
for(Contact con : accs.Contacts) {
if(accs.Coverage_Lead__c != NULL) {
accs.OwnerId = accs.Coverage_Lead__c;
con.OwnerId = accs.Coverage_Lead__c;
}
else if(accs.Coverage_Lead__c == NULL) {
accs.OwnerId = accs.LastModifiedById;
con.OwnerId = accs.LastModifiedById;
}
}
}
Thanks in Advance.