I have a requirement where I have the custom field 'Account Owner' on Account object and I have the same field on Child Object Opportunity.When I change the Account Owner on Account then it should update the Account Owner on all Child Records.
For this I have written a Trigger(After Update) on Account Object.
Private void UpdateAccountOwnerOnOpportunity(Map<Id, SObject> newItems, Map<Id, SObject> oldItems) {
Map<Id,Opportunity> optMap=new Map<Id,Opportunity>();
Map<Id,Account> actMap=new Map<Id,Account>();
for(SObject newObj :newItems.values()){
Account newAccountObj=(Account)newObj;
Account oldAccountObj = (Account)oldItems.get(newObj.Id);
if(newAccountObj.Sales_Person__c!=null && (newAccountObj.Sales_Person__c != oldAccountObj.Sales_Person__c)){
actMap.put(newAccountObj.Id,newAccountObj);
}
}
if(!actMap.isEmpty()){
for(Opportunity opt:[Select Id,AccountId,Sales_Person__c from Opportunity where AccountId IN:actMap.keySet()]){
Account ac = actMap.get(opt.AccountId);
opt.Sales_Person__c=ac.Sales_Person__c;
optMap.put(opt.Id,Opt);
}
update optMap.values();
}
}
The above code is working as expected. but fails in below scenario.
When we designed the application,we had migrated some Old Opportunities records from Legacy Environments to our New Org by Bypassing all Validations and Alomost all of the old Legacy Records are at 'Closed' Stage.All these Opporunities Refer to certain Account.
So If I update Account Owner Field on Account which has Legacy Opportunity Records then I face FIELD_CUSTOM_VALIDATION_EXCEPTION error message on screen and which is oblivious as we have now enabled all validation rule .
My Expectation is Even If I have such existing records in my Org & If I change Owner then it must change Account Owner on all existing Opportunity Records.
I am looking for Best Apprach of how to bypass validations for Opportunity Records when I update the Update from Account exiting.
Can someone please suggest what needs to be done when we deal with Legacy Org Records?