When merging accounts, I want to be able to update the owner of the re-parented opportunities, and custom objects under account to the owner of the "winning" account.
My current trigger runs "after delete" and will grab all the associated opportunities for each account and associate them to the owner. This doesn't provide the distinction between the child records, the opportunities that were not re-parented should remain the same and not have their owners modified.
One thing that I was considering is creating a field that will be populated with a value "before delete" and access those in my "after delete" trigger. I thought this solution would be rather messy and was wondering if there was a cleaner way to figure out which records belonged to the losing account in a merger.
Thanks in advance!
Code:
trigger updateOwnerMerge on Account (after delete) {
//Create List of account IDs that have been merged
List<Id> acctIDs = new List<Id>();
for (Account a : Trigger.Old) {
//If the Record has been deleted through a merge, add winning account of merge to List
if (a.MasterRecordId != NULL) {
acctIDs.add(a.MasterRecordId);
}
}
//If there are any accounts that have been merged
if(acctIDs.size() != 0) {
//Map to associated account ID to account owner
Map<ID, ID> accountOwner = new Map<ID, ID>();
//Query SOQL to find all potential accounts
List<Account> accounts = [Select ID, OwnerID from Account where ID in: acctIds];
for (Account acc : accounts) {
//Add account ID, Owner association to map
accountOwner.put(acc.Id, acc.OwnerId);
}
update updatedApps;
//Find all opportunities related to account, update owner of open opportunities
List<Opportunity> opps = [Select ID, OwnerID, AccountID, IsClosed from Opportunity where AccountID in: accounts];
List<Opportunity> updatedOpps = new List<Opportunity>();
for (Opportunity opp: opps) {
if(!opp.IsClosed) {
if(opp.OwnerID != accountOwner.get(opp.AccountID)) {
opp.OwnerID = accountOwner.get(opp.AccountID);
updatedOpps.add(opp);
}
}
}
update updatedOpps;
}
}
Best Answer
You better write a trigger on Opportunity. Check if owner is same as owner of account, if not-make it same.