You need to sign in to do that
Don't have an account?
Christina Tomaselli
self-reference from trigger
I have a trigger that I am using to update related accounts (based on a custom field not a lookup) so I am using SOQL but when i try and execute I am getting a self-reference error:
trigger UpdateBusinessAgreement on Account (before update) {
for (Account a : Trigger.new){
String TIN = a.Tax_ID_Number__c;
String AID = a.Id;
List<Account> matchingAccounts = [SELECT ID, Business_Agreement_Completed__c, Tax_ID_Number__c FROM Account WHERE ID <>: AID AND Tax_ID_Number__c =: TIN];
if (a.Business_Agreement_Completed__c == 'Received - Complete'){
for (Account Acc : matchingAccounts){
Acc.Business_Agreement_Completed__c = 'Received - Complete';
update acc;
}
}
}
}
trigger UpdateBusinessAgreement on Account (before update) {
for (Account a : Trigger.new){
String TIN = a.Tax_ID_Number__c;
String AID = a.Id;
List<Account> matchingAccounts = [SELECT ID, Business_Agreement_Completed__c, Tax_ID_Number__c FROM Account WHERE ID <>: AID AND Tax_ID_Number__c =: TIN];
if (a.Business_Agreement_Completed__c == 'Received - Complete'){
for (Account Acc : matchingAccounts){
Acc.Business_Agreement_Completed__c = 'Received - Complete';
update acc;
}
}
}
}
Greetings!
You do not need to write the logic to retrieve the Accounts as the records are already there in the Trigger.New.So,can you please try by skipping the Select Statement and update the Accounts records directly.
Reference:https://developer.salesforce.com/forums/?id=906F00000008ziKIAQ
Kindly mark it as best answer if it helps so that it can help others in the future.
Warm Regards,
Shirisha Pathuri
1. Do not put SOQL in the loop. This is the best practie recommened by Salesforce. Otherwise, you will easily get SOQL 101 issue when doing batching process.
2. Use AFTER Update in this case, because you are going to change other records other than the updating records themself.
Please try the code below:
some reasoning.
1. it seems to be that we want to move to a state of "received - complete". If we are already at that status, why do another update which will risk kicking things into a recursive loop. So test for the status being already set and only update those values that require the update
2. to exclude records that fire the original trigger, we can use a NOT IN as a filter for the SOQL.
so based on the above, if we consider updating a record 1, (and assume there is a 2nd record in database), the trigger fires, works out the status change and then goes and finds the other record. The query will return only that record. Once that record is then updated by the after trigger, the update trigger will fire again. The first loop will run. And then the SOQL query will run, but return no values. And therefore no more DMLs will run and the risk of recursion is avoided.
regards
Andrew