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
Amita TatarAmita Tatar 

get parent Account name from id and update it in a field using trigger

Hi all,

I have a requirement where i want to update my account name field along with its parent account name. I want to display parent account name in the bracket of the child account name. I wrote below trigger
. It Is getting updated with id of parent account and i want name. Please tell me whats wrong
trigger UpdateAccount on Account (before insert) {


for(Account a:Trigger.New){

if( a.Parent2__c != null){
   
  a.ParentId = a.Parent2__c;
  
  string parentName = a.Parent.Name;
  a.Name = a.Name +'(' + parentName + ')'; 
  system.debug('*******************'+parentName );
  

}
}



}
Thanks,
Amita
 
Shiva RajendranShiva Rajendran
Hi Amita,
If my understanding is correct
you have parent2__c as a account lookup and it is supposed to be the same account parentId.
Then this simple modification will work at line 10

  string parentName = a.Parent2__r.Name;

else if you want the answer only through the account.ParentId ,then use the below code
 
Trigger UpdateAccount on Account(before insert)
{

Map<ID, Account> ParentAccountMap = new Map<ID, Account>([Select ID,name From Accoun t where parentId in :Trigger.New.keySet()]);
for(Account a:Trigger.New)
{
  if(a.ParentId!=null)
{
   Account ParentAcc=ParentAccountMap.get(a.ParentId);
 String parentName= ParentAcc.name;
a.Name= a.Name + '(' + parentName + ')';
system.debug('****************'+parentName);

}


}


}
Also few key points to note here
Trigger name is written as  UpdateAccount whereas you are using it for (before insert) . It is not a good naming convention.

let me know if you have any further queries.

Thanks and Regards,
Shiva RV