I have a setup were we have Accounts and Person Accounts. The Person Accounts are in some cases linked to Accounts via AccountContactRelation. If the owner of a special record type of Accounts changes we want to change the owner of all related Person Accounts to the same owner as the new Account owner.
I've written an APEX trigger for this and if the current owners of all related Person Accounts are the same user, everything works perfectly. On the other hand if the some of the Person Accounts have different user/s as owners then the trigger fails with the error message:
ArmAccountOwnerChange: execution of BeforeUpdate, caused by: System.DmlException: Update failed. First exception on row 0 with id 0010Q0000050J0FQAU; first error: INVALID_FIELD, All accounts must have the same current owner and new owner.: [OwnerId] Trigger.ArmAccountOwnerChange: line 23, column 1
Here is the trigger. Any idea why this is happening?
trigger ArmAccountOwnerChange on Account (before update) {
List<AccountContactRelation> acr = New List<AccountContactRelation>();
List<Account> acc = New List<Account>();
RecordType rec = [Select Id From RecordType Where DeveloperName = 'ARM_Account' Limit 1];
for(Account a: Trigger.new) {
if(a.OwnerId != Trigger.oldMap.get(a.id).OwnerId && a.RecordTypeId == rec.id) {
acr = [SELECT Id, ContactId From AccountContactRelation Where AccountId = :a.id];
If(acr.size() > 0) {
for(AccountContactRelation b: acr) {
acc.addAll([Select Id, OwnerId From Account Where PersonContactId = :b.ContactId]);
}
}
If(acc.size() > 0) {
for(Account c: acc) {
c.OwnerId = a.OwnerId;
}
}
update acc;
}
}
}