+ Start a Discussion
Syed F RazaSyed F Raza 

Assign Account ID to a contact using trigger

HI All,

I am writing a trigger where if the Contact being created is not related to an account, then we should assign this contact to a particular account:
 
trigger trigger_Contact1 on Contact (before insert) {


      List<contact> conlist = new List<contact>(); 
      for(Contact con :trigger.new){
      if(Accountid==null)
      Account.id=0015G00001dSXtWQAW;
      conlist.add(con);
      }
     
    insert conlist;
}

The account id I have mentioned is of an account to which I would like to assign all contacts to in case if the Account is not selected for such contacts at time of insert.
 
Danish HodaDanish Hoda
hi Raza, you can refer below code - 
trigger trigger_Contact1 on Contact (before insert) {
      //List<contact> conlist = new List<contact>(); 
      for(Contact con :trigger.new){
             if(con.Accountid==null && String.isBlank(con.Accountid)){
                     con.AccountId = '0015G00001dSXtWQAW';
             }
      }
    //insert conlist;
    //no need to explicitly insert/update the same record in trigger. Apex trigger automatically does the job
}
CharuDuttCharuDutt
Hii Raza
Try Below Trigger Code
trigger  trigger_Contact1 on Contact (before insert) {
    if(trigger.IsInsert && Trigger.IsBefore){
        for(contact con : trigger.new){
           if(con.AccountId == Null){
            con.AccountId = '0015G00001dSXtWQAW';
           } 
        }
    }
}

Please Mark It As Best Answer If It Helps
Thank You!