I have created a trigger for the following behavior in my Salesforce org: When the user changes the Account Owner, it automatically changes the Contract Owner on the related contracts before update. However if some mandatory fields are not filled in the contract page the user received a red system error and that's what Iwould like to enhance.
I have written that trigger, don't hesitate to correct it because I am biginning in sAlesforce Apex code and I need to learn! Thanks a lot
trigger TriggerUpdateContractOwnerFromAcount on Account (Before Update) {
for(Account Acc :Trigger.new){
List<Contract> C = [select id, ownerid, AccountId,Account_Number__c,Contact__c,Name,status,StartDate,EndDate,OwnerExpirationNotice,
Contract_Type__c,Annual_Value__c,Annual_Volume__c,UOM__c,Estimate_of_annual_PBIT__c,Capital_Required__c,Budgeted__c,
Other_Costs__c from Contract where Account.id = :Acc.Id ];
for (Contract Ctr : C)
if(Ctr.Ownerid != Acc.Ownerid & Ctr.EndDate !=null||Ctr.Account_Number__c!= null||Ctr.Contact__c!= null||Ctr.Name!= null||Ctr.status!=null||Ctr.StartDate!= null||Ctr.EndDate!=null||Ctr.OwnerExpirationNotice!=null||
Ctr.Contract_Type__c!= null||Ctr.Annual_Value__c!=null||Ctr.Annual_Volume__c!=null||Ctr.UOM__c!= null||Ctr.Estimate_of_annual_PBIT__c!=null||Ctr.Capital_Required__c!= null||Ctr.Budgeted__c!=null||
Ctr.Other_Costs__c!=null){
//Acc.owner.Adderror('Please complete mandatory fields on Contract before Changing the Account Owner');
Ctr.Ownerid= Acc.Ownerid;
}
update C;
for (Contract Ctr : C)
if(Ctr.Ownerid != Acc.Ownerid & Ctr.EndDate ==null||Ctr.Account_Number__c== null||Ctr.Contact__c== null||Ctr.Name==null||Ctr.status==null||Ctr.StartDate== null||Ctr.EndDate==null||Ctr.OwnerExpirationNotice==null||
Ctr.Contract_Type__c==null||Ctr.Annual_Value__c==null||Ctr.Annual_Volume__c==null||Ctr.UOM__c== null||Ctr.Estimate_of_annual_PBIT__c==null||Ctr.Capital_Required__c== null||Ctr.Budgeted__c==null||
Ctr.Other_Costs__c==null){
//add error message if mandatory fields are empty in related contract
Acc.owner.Adderror('Please complete mandatory fields on Contract before Changing the Account Owner');
}
}
}
And this is the error I get on the page "Select New Owner" for Transfer (=Link Change owner on account page) :
Review all error messages below to correct your data.
Error: Apex trigger TriggerUpdateContractOwnerFromAcount caused an unexpected exception, contact your administrator: TriggerUpdateContractOwnerFromAcount: execution of BeforeUpdate
caused by: System.DmlException: Update failed. First exception on row 0 with id 800O00000002Z01IAE; first error: FIELD_FILTER_VALIDATION_EXCEPTION, Value does not exist or does not match filter criteria.: [AccountId]: Trigger.TriggerUpdateContractOwnerFromAcount: line 15, column 1
Hope this make sense, many thanks.