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
Hari N 20Hari N 20 

Trigger to Insert record in Contact from Account

Hi All,
I want insert record and update record.
When I create a record in Account, I want create same record in Contact also.
I want to Update the same record in Account and the contact also should update.

Please share if any one has syntax for this.

Thanks in Advance

Regards
Hari
Best Answer chosen by Hari N 20
karthikeyan perumalkarthikeyan perumal
Hello, 

This is final Trigger, this code works 100%. 
 
trigger CreateANDUpdateAccountContact on Account (after insert, after update){
List<Id> accountIds = new List<Id>();

for(Account acc : trigger.new){
        accountIds.add(acc.id);
    }
    
Map<ID, Account> mapAccounts = new Map<ID, Account>([SELECT Id, Name,My_Name__c  FROM Account where Id IN :accountIds]);

if(Trigger.isInsert){

    List<Contact> ct = new List <Contact>();

        for(Account acc : trigger.new){
    
        Contact c = new Contact(LastName = 'Test',
                    AccountId=acc.Id,
                    Fax='232323'
                    );

         ct.add(c);
         }
   
    insert ct; 
}
if(Trigger.isUpdate){

List<Contact>  lstContacts = [SELECT Id, name,LastName,AccountId FROM Contact where AccountId IN :accountIds];
For(Contact con : lstContacts)
  {
     Account acc = mapAccounts.get(con.AccountId);
     con.LastName= acc.My_Name__c;
     
  }
  update lstContacts;
}


}



Hope this will help you
Mark Best ANSWER if its works for you.

Thanks
karthik
 

All Answers

karthikeyan perumalkarthikeyan perumal
 
Hello, 

Use below code, 
 
trigger CreateANDUpdateAccountContact on Account (after insert, after update){
List<Id> accountIds = new List<Id>();

for(Account acc : trigger.new){
        accountIds.add(acc.id);
    }
if(Trigger.isInsert){

    List<Contact> ct = new List <Contact>();

    
        Contact c = new Contact(LastName = 'Test',
                    AccountId=accountIds[0],
                    Fax='232323'
                    );

        ct.add(c);
   
    insert ct; 
}
if(Trigger.isUpdate){

List<Contact>  lstContacts = [SELECT Id, name FROM Contact where AccountId IN :accountIds];
For(Contact con : lstContacts)
  {
     
     con.LastName= 'TestName';
  }
  update lstContacts;
}


}


 
Hope this will help you, 

Mark Best ANSWER if its work for you. 

Thanks
karthik
 
Hari N 20Hari N 20
Hi Karthikeyan,
for Last Name I want to give my customfield like Filed__c
how can I do?
karthikeyan perumalkarthikeyan perumal
Hello, 

Query the customField name here, like below, 
 
if(Trigger.isUpdate)
{
List<Contact>  lstContacts = [SELECT Id, LastName,Field1__c,Field2__c FROM Contact where AccountId IN :accountIds];
For(Contact con : lstContacts) 
{ 
con.LastName= 'TestName'; 
con.Field1__c= 'Testvalue1';
con.Field2__c = 'Testvalue2';
} 
update lstContacts; 
}
Or you want assign Account Filed value to Contact Field 

Use Below
 
trigger CreateANDUpdateAccountContact on Account (after insert, after update){
List<Id> accountIds = new List<Id>();

for(Account acc : trigger.new){
        accountIds.add(acc.id);
    }
    
Map<ID, Account> mapAccounts = new Map<ID, Account>([SELECT Id, Name,Field1__c,Field2__c  FROM Account where Id IN :accountIds]);

if(Trigger.isInsert){

    List<Contact> ct = new List <Contact>();

    
        Contact c = new Contact(LastName = 'Test',
                    AccountId=accountIds[0],
                    Fax='232323'
                    );

        ct.add(c);
   
    insert ct; 
}
if(Trigger.isUpdate){

List<Contact>  lstContacts = [SELECT Id, name FROM Contact where AccountId IN :accountIds];
For(Contact con : lstContacts)
  {
     Account acc = mapAccounts.get(con.AccountId);
     con.LastName= acc.Name;
     con.Field1__c=acc.Field1__c;
     con.Field2__c=acc.Field2__c  ;
  }
  update lstContacts;
}


}

Hope it will clear,
Mark Best Answer if its works for you.

Thanks
karthik

 
Hari N 20Hari N 20
Hi Karthikeyan,
Thank you very much for your time.
In line number 15, I assigned "Last Name = acc.Field__c". It is showing error as no variable exist. But it is there in Account object.

even I gave my custom field in lin number 30 also. I got the following error while updating

Error Snap
karthikeyan perumalkarthikeyan perumal
Hello, 

Add LastName in that Query, like below

List<Contact>  lstContacts = [SELECT Id, name,LastName FROM Contact where AccountId IN :accountIds];

Hope it will solve your issue, 

let me know if you need anything,

Thanks
karthik
 
Hari N 20Hari N 20
trigger CreateANDUpdateAccountContact on Account (after insert, after update){
List<Id> accountIds = new List<Id>();


Map<ID, Account> mapAccounts = new Map<ID, Account>([SELECT Id, Name,My_Name__c  FROM Account where Id IN :accountIds]);

if(Trigger.isInsert){

   for(Account acc : trigger.new){
        accountIds.add(acc.id);
    
    
    List<Contact> ct = new List <Contact>();

    
        Contact c = new Contact(LastName = acc.My_Name__c,
                    AccountId=accountIds[0],
                    Fax='232323'
                    );

        ct.add(c);
   
  insert ct; 
  }  
}
if(Trigger.isUpdate){

List<Contact>  lstContacts = [SELECT Id, name, LastName FROM Contact where AccountId IN :accountIds];
For(Contact con : lstContacts)
  {
     Account acc = mapAccounts.get(con.AccountId);
     con.LastName= acc.My_Name__c;
           
  }
  update lstContacts;
}


}


This is the code I have written
Now, It is working
But, when I am updating a the same record, Last name is not updating even I changed My_Name__c field in Account,
But, It saving with out error and with no changes
karthikeyan perumalkarthikeyan perumal
Hello, 

This is final Trigger, this code works 100%. 
 
trigger CreateANDUpdateAccountContact on Account (after insert, after update){
List<Id> accountIds = new List<Id>();

for(Account acc : trigger.new){
        accountIds.add(acc.id);
    }
    
Map<ID, Account> mapAccounts = new Map<ID, Account>([SELECT Id, Name,My_Name__c  FROM Account where Id IN :accountIds]);

if(Trigger.isInsert){

    List<Contact> ct = new List <Contact>();

        for(Account acc : trigger.new){
    
        Contact c = new Contact(LastName = 'Test',
                    AccountId=acc.Id,
                    Fax='232323'
                    );

         ct.add(c);
         }
   
    insert ct; 
}
if(Trigger.isUpdate){

List<Contact>  lstContacts = [SELECT Id, name,LastName,AccountId FROM Contact where AccountId IN :accountIds];
For(Contact con : lstContacts)
  {
     Account acc = mapAccounts.get(con.AccountId);
     con.LastName= acc.My_Name__c;
     
  }
  update lstContacts;
}


}



Hope this will help you
Mark Best ANSWER if its works for you.

Thanks
karthik
 
This was selected as the best answer
amol salveamol salve

Hello Heri,
      As per your requirement..when u insert Account record,Contact record automatically will be created and whenever you update Account record contact record will be update..but in contact their is only field related to account thats is Master detail with account..and which is automatically updated..I used scenario that suppose you had created one account record then with same name contact record will be updated..and for update if you change account name then contact name will be automaticaly update with updated account name..When you update Account its required to update only those contact,which is created by that account when it created.to uniquely indentyfy I had created one checkbox field named as Is_primary__c,So when ever you update Account it will update only those contact which is created when related account is created 

please use below code for achiving this functionality

Trigger :

trigger CreateAndUpdateAccountContact on Account (after insert, after update) {
    
    if( trigger.isAfter ) {
        
        if ( trigger.isInsert ) {
        
            CreateAndUpdateAccountContactHandler createAndUpdateAccountContactHandlerInstance = new CreateAndUpdateAccountContactHandler();
            createAndUpdateAccountContactHandlerInstance.createContactAfterInsertAccount ( trigger.new );
        }
        else if ( trigger.isUpdate ) {
            
            for( Account accObj : trigger.new ) {
            
                if( trigger.oldmap.get ( accObj.Id ).Name .compareTo ( trigger.newmap.get ( accObj.Id ).Name ) != 0 ) {
                
                    CreateAndUpdateAccountContactHandler createAndUpdateAccountContactHandlerInstance = new CreateAndUpdateAccountContactHandler();
                    createAndUpdateAccountContactHandlerInstance.updateContactAfterUpdateAccount ( trigger.new, trigger.old );
                }
            }
        }
    }
}




Handler :

public class CreateAndUpdateAccountContactHandler {
    
    public set < Id > accountIdSet = new set < Id > ();
    public list < Contact > contactList = new list < Contact > ( );
    public map < string, Contact > stringVsContactMap = new map < string, Contact > ( );
    
    public void createContactAfterInsertAccount ( list < Account > accountList ) {
    
        for ( Account accObj : accountList ) {
            Contact conObj = new Contact ( LastName = accObj.Name, accountId = accObj.Id, Is_primary__c = true );
            contactList.add ( conObj );
        }
        Database.insert ( contactList,false ) ;
    }
    
    public void updateContactAfterUpdateAccount ( list < Account > accountList, list < Account > oldAccountList ) {
        
        for ( Account accObj : accountList ) {
            
            accountIdSet.add ( accObj.Id ); 
        }
        
        for ( Contact conObj : [ SELECT Id, LastName, account.Name FROM Contact WHERE accountId IN : accountIdSet AND Is_primary__c = true ] ) {
            
            if ( conObj.LastName.compareTo ( conObj.account.Name ) != 0 ) {
            
                 conObj.LastName = conObj.account.Name;
                 contactList.add ( conObj );
            }
        }
        DataBase.update ( contactList );
    }
}

Thank you,

Amol B. Salve 

Hari N 20Hari N 20
Hi Karthikeyan,
I made some changes to my trigger.
If I dont have LastName then I am creating only Account.
Now, I am editing same record and providing Lastname to Contact to get create contact.
But, Contact is not creating.
I tried multiple ways.
Please help me what changes I need to do for the above code
karthikeyan perumalkarthikeyan perumal
Hello, 

Use this updated code, 
 
trigger CreateANDUpdateAccountContact on Account (after insert, after update){
List<Id> accountIds = new List<Id>();

for(Account acc : trigger.new){
        accountIds.add(acc.id);
    }
    
Map<ID, Account> mapAccounts = new Map<ID, Account>([SELECT Id, Name,My_Name__c  FROM Account where Id IN :accountIds]);

if(Trigger.isInsert){

    List<Contact> ct = new List <Contact>();

        for(Account acc : trigger.new){
    
        Contact c = new Contact(LastName = 'Test',
                    AccountId=acc.Id,
                    Fax='232323'
                    );

         ct.add(c);
         }
   
    insert ct; 
}
if(Trigger.isUpdate){

List<Contact>  lstContacts = [SELECT Id, name,LastName,AccountId FROM Contact where AccountId IN :accountIds];
if(lstContacts.Size()>0)
{
For(Contact con : lstContacts)
  {
     Account acc = mapAccounts.get(con.AccountId);
     con.LastName= acc.My_Name__c;
     
  }
  update lstContacts;
  }
  else
  {
  List<Contact> ct = new List <Contact>();

        for(Account acc : trigger.new){
    
        Contact c = new Contact(LastName = acc.My_Name__c+TestContct,
                    AccountId=acc.Id,
                    Fax='232323'
                    );

         ct.add(c);
         }
   
    insert ct; 
  }
}


}
Hope this will help you 

Thanks
karthik
 
Hari N 20Hari N 20
Thank you Karthik.
Its working