Saturday, December 1, 2018

Apex Trigger On Account To Fetch Parent Hierarchy

Trigger : Use Case - Fetch Parent Hierarchy on Account Object. 

APEX Trigger to Fetch the Parent Hierarchy of a Particular Account and Populates all the Parent Names in a Custom Field on Account.
Before Writing a Trigger, Make sure that you create a Custom Text Field on Account Object.

Here I have Created a Parent_Hierarchy__c Custom Text Field on Account Object.

Source code

 /*   
  * Developer : Dev Pro  
  * Use Case : Trigger To Fetch Parent Hierarchy, and Update All Parent Names on Child Account (Custom Field : Parent_Hierarchy__c )  
  */  
 trigger ParentHierarchy on Account (before update, before insert)   
 {  
   for(Account currentAcc : Trigger.new)  
   {  
     Account acc = trigger.new[0];  
     String ParentName = 'Parent Names : ' +acc.Name+ ',' ;  
     //String parentName = acc.Name;  
     //String parentName = acc.Name + acc.Id;  
     if(acc.ParentId!=null)  
     {  
       do{  
         acc = [SELECT ID, Name, ParentId FROM Account WHERE Id = : acc.ParentId];  
         //parentName += acc.Name + acc.Id;  
         parentName += acc.Name;  
         System.debug('Parent Names : ' +acc.Name+',');  
       }while(acc.ParentId!=null);  
     }   
     trigger.new[0].Parent_Hierarchy__c = ParentName;  
   }  
 }  


EmoticonEmoticon