+ Start a Discussion

can anyone tell me whats wrong in below code

The error I got here is 
SELF_REFERENCE_FROM_TRIGGER, Object is currently in trigger AccountTrigger, therefore it cannot recursively update itself: []: Class.classname.automateAccOwnership: line xx, column 1
public static void automateAccOwnership(Account[] updatedAccounts){
            set<id> accIds = new set<id>();
            for(account acc:updatedAccounts){
                if(!acc.Account_Team_Exception__c) accIds.add(acc.id);
    Map<id, user> userMap = new map<id,user>([select id, name from user where isActive=true]);
             list<account> accWithTeam= new list<account>([select id,name, checkbox1__c,type,Account_Team_Exception__c,(SELECT AccountAccessLevel,AccountId, Id,TeamMemberRole,UserId FROM AccountTeamMembers) from account  where id in:accIds]); 
            for(account acc: accWithTeam){
                for(AccountTeamMember ATM : acc.AccountTeamMembers ){               
        if(acc.checkbox1==true  && atm.TeamMemberRole=='RSD-BPSTN/CPSTN' ) {                        
                        acc.ownerid = atm.UserId ;
           if(acc.type=='Reg Co - Tax Haven' ){ 
           for(user user:userMap.values())if(user.name== 'username') 
           acc.ownerId = user.id;             
     update accWithTeam; // this update statemet causing recursion

I appreciate your help.
Thank you.

It looks like the code is going in loop.

If I understand the your code, you basically changing the ownership of the account based on the certain criteria right?, if yes, why don't you do this using the trigger then you will change the owner field.

if you have to call out to this method then put an exist condition in this method like it has to execute only once.

I hope this helps

"Appreciate your feedback"
Balagopal GBalagopal G


you can use the checkRecursive class to avoid recursive calls in Trigger.

please find this :- https://help.salesforce.com/articleView?id=000133752&language=en_US&type=1