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
Rahul Sethi 11Rahul Sethi 11 

I am trying to build a trigger on Contact object. So, whenever a user enters a contact record, its related account name field gets updated with contact last name.

Please have a look at the code below: 

trigger addcontactlastname2accountname on Contact(before insert){

    Set<ID> contactid_lst = new Set<ID>();
    List<Account> account_lst = new List<Account>();
    Map<ID, Account> accountmap = new Map<ID, Account>();

    for(Contact c: Trigger.New){
        
        contactid_lst.add(c.AccountID);
    }

    account_lst = [Select ID, Name from Account where ID IN: contactid_lst];


    for(Contact c: Trigger.New){


        Account objacct = new Account();

        objacct = accountmap(account_lst).get(c.AccountID);
        
        objacct.Name = objacct.Name + '' + c.lastname;
        

    }

}
v varaprasadv varaprasad
Hi Rahul,

please check once following code : 
 
trigger addcontactlastname2accountname on Contact(before insert){

    Set<ID> contactid_lst = new Set<ID>();    
    Map<ID, Account> accountmap = new Map<ID, Account>();

    for(Contact c: Trigger.New){
	    if(c.AccountID != null){
		   contactid_lst.add(c.AccountID);
		}
        
        
    }

    accountmap = [Select ID, Name from Account where ID IN: contactid_lst];


    for(Contact c: Trigger.New){
	  c.lastname = accountmap.get(c.AccountID).name;      

    }

}

Hope this helps you!

Thanks
Varaprasad
For Support: varaprasad4sfdc@gmail.com
 
Srikanth sfdc 32Srikanth sfdc 32
Hi Rahul 

please try this code 


trigger updateaccountname on Contact (before insert) 
{
    set<id> conids = new set<id>();
  
  list<schema.contact> conlst = new list<schema.contact>();  
  
 
    
    for(schema.contact c : trigger.new)
    {
       conids.add(c.accountid);
       
    }   
    
    schema.Account a = new schema.account();
    
    
 list<schema.Account>  act = [select id,name from account where id IN:conids];
  
  for(schema.contact ct : trigger.new)
  {
      a.name = ct.lastname;
       
      act.add(a);
  }
  
    insert act;
    
        for(schema.account acc : act)
        {
           for(schema.contact cc : trigger.new)
           {
              cc.accountid = acc.id;
              
              
           }
           
         }
                
   
}
Hope this will works well

Thanks & regards

k.Srikanth