function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sylvie SerpletSylvie Serplet 

Trigger on Account to update Parent Account

Hi All,
I try to show on a Parent Account (checkbox) that it has a child Account in the hierachy of Accounts.
Below is my trigger but it does not work.
I have also tried Process Builder but could not make the criterias right.
Any Ideas?
trigger UpdateHierachyAccount on Account (after insert, after update) {
    
    Set<Id> accountIds = new Set<Id>();
    
    for (Account acc : Trigger.new) {
        if (acc.ParentId != null){
            accountIds.add(acc.Id);
        }
        
        List<Account> accounts = [select id, Has_Child_Account__c from account where id in :accountIds ];
        
        for(Account a : accounts) {        
            a.Has_Child_Account__c = true;
        }   
        update accounts;
    }
}

Thank you in advance for your help.
Sylvie
Best Answer chosen by Sylvie Serplet
sfdcMonkey.comsfdcMonkey.com
Hi sylvie, 
first you have need to create apex class for Avoid Recursive Trigger Calls, 

apex class:
public Class checkRecursive{
    private static boolean run = true;
    public static boolean runOnce(){
    if(run){
     run=false;
     return true;
    }else{
        return run;
    }
    }
}

trigger (updated):
trigger UpdateHierachyAccount on Account (after insert, after update) {
     if(checkRecursive.runOnce()) {
    Set<Id> accountIds = new Set<Id>();
    
    for (Account acc : Trigger.new) {
        if (acc.ParentId != null){
            accountIds.add(acc.ParentId);
        }
      if(accountIds.size() > 0 ){  
        List<Account> accounts = [select id, Has_Child_Account__c from account where id in :accountIds ];
        
        for(Account a : accounts) {        
            a.Has_Child_Account__c = true;
        }   
        update accounts;
      }
    }
    }
}
ref : https://help.salesforce.com/articleView?id=000133752&language=en_US&type=1
Thank, let us know if it helps you 
http://sfdcmonkey.com