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
meghanadh Gmeghanadh G 

Whenever contact is inserted/updated, and if contact first name is blank, then auto populate the contact first name with Account name. I've written the following trigger code. can you suggest the best approach for it

Trigger poppulateFirstNameFromAccount on Contact (before insert, before update)
{
    for(Contact Con: trigger.new)
    {
    if(String.isBlank(contact.FirstName))
        {
        contact.FirstName = contact.Account.Name;
        }
    }
}
HarshHarsh (Salesforce Developers) 
Hi Meghanadh,
you can use the following code, It will work as per your request.
//trigger

Trigger poppulateFirstNameFromAccount on Contact (before insert, before update)
{
    if(trigger.IsBefore && (trigger.IsInsert || trigger.IsUpdate)){
        poppulateFirstNameFromAccountHandler.Demo(trigger.new);
    }
}

// Handler class

public class poppulateFirstNameFromAccountHandler {   
    public static void Demo(List<Contact> newcon){
        for(Contact con:newcon)  {
            if (con.FirstName == null){
                List<Account> retrivedata = [select id, Name from Account where Id =: con.AccountId];
                for(Account acc: retrivedata){
                    con.FirstName = acc.Name;
                }
            }
        } 
    }
}

Create one trigger and one handler class having the name  "poppulateFirstNameFromAccountHandler".

Please mark it as Best Answer if the above information was helpful.

Thanks.
 
Arun Kumar 1141Arun Kumar 1141

Hi Meghanadh,

You can refer to the below code:

At the time of writing code you should avoid SOQL queries inside the loop. It may exceed the govener limit.

Trigger poppulateFirstNameFromAccount on Contact (after insert, before update)
{
    if(trigger.IsBefore && (trigger.IsInsert || trigger.IsUpdate)){
        poppulateFirstNameFromAccountHandler.Demo(trigger.new);
    }
}

public class poppulateFirstNameFromAccountHandler {   
    public static void Demo(List<Contact> conList){

   List<Id> accountIds = new List<Id>();

  for(Contact con : conList){
          accountIds.add(con.AccountId);
}


  List<Contact> accData = [select id, Account.Name from Contact where AccountId IN : accountIds];
        
          
for( Contact con : conList){
          if(con.firstName == null){
                   for(Account acc : accData){
                                if(acc.id == con.AccountId){
                                              con.firstName = acc.Name;
                                      }
                        }
               }
       }
          update conList;
        }
}

Please mark it as best answer if it helps.

Thanks,