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
NyshaaNyshaa 

On creating a record in one object automatically a record should be created on the other object.

Create two Objects say Obj1(Parent) and Obj2(Child) having similar fields. On creating record of Obj1, associated Obj2 record should be created and vice versa. Additionally, updates should also be in sync i.e. updating the parent should reflect in the child and vice versa.
 

How can I achieve this requirement.

Thanks in Advance!

RituSharmaRituSharma
You may use process builder for this. Create process builder on both the objects to keep Obj1 and Obj2 in sync.
AbhishekAbhishek (Salesforce Developers) 
You can try this sample code,

trigger CreateAccountContact on Account (after insert, after update){

if(Trigger.isInsert){

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

    for(Account acc : trigger.new){

        Contact c = new Contact(LastName = acc.name,
                    AccountId=acc.id,
                    Fax=acc.Fax,
                    MailingStreet=acc.BillingStreet,
                    MailingCity=acc.BillingCity,
                    /* similarly add all fields which you want */
                    MailingState=acc.BillingState,
                    MailingPostalCode=acc.BillingPostalCode,
                    MailingCountry=acc.BillingCountry,
                    Phone=acc.Phone);

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

It might help you.

 
Mahesh GorrepatiMahesh Gorrepati
Check the code::- 


Class code::-
/*
* @ Author : Gorrepati Mahesh
* @ Description : This Class Contains the Handler Methods for after insert and updation od the accoount and contact reocrds and vice versa,
* to be referenced inside the Lead Triggers.
* @ Version : 1.0
* @ Created Date : 04/4/2023
* @ Reference : AutoCOntactcreation from account and vice versa.
* @ Modified By :
* Modified By Modified Date Reason
* ----------------------------------------------------------------------
*/
public class recordsCreationbtntwoobjectsViceVersa {
    
    public static boolean firstRun = true;
    /*
* @ Method Name : gererrormsgs
* @ Description : This method is used to show the debug messages .
* @ Parameters:
* @Param Name :database.SaveResult[] lstresults
* @ Returns : N/A
* @ Throws : NA
* @ References : AutoLeadConversion
* @ Version : 1.0
*/
    
    public static void geterrormsgs( database.SaveResult[] lstresults)
    {
        if(lstresults.size()>0)
        {
            for(database.SaveResult res: lstresults)
            {
                if(res.issuccess())
                {
                    system.debug('the records created ' + res.getid());
                } else 
                {
                    for(database.Error err : res.geterrors())
                    {
                        system.debug('the error records'+ err.getMessage());
                        system.debug('The error code is ' + err.getStatusCode());
                        system.debug('The error fields is ' + err.getFields());
                    }
                }
            }
            
        }
    }
    
    
    /*
* @ Method Name : createcontactrecords
* @ Description : This method is used tocreatecontact records.
* @ Parameters:
* @Param Name :lstacc
* @ Returns : N/A
* @ Throws : NA
* @ References : Autocontactcreation
* @ Version : 1.0
*/
    public static void createcontactrecords(list<account> lstacc)
    {
        if(!lstacc.isempty())
        {
            
            
            list<contact> lstcontacts= new list <contact> ();
            for(account acc: lstacc)
            {
                contact con = new contact ();
                con.LastName=acc.name +'contact';
                con.AccountId=acc.id;
                lstcontacts.add(con);
            }
            
            database.SaveResult[] results = database.insert(lstcontacts,false);
            recordsCreationbtntwoobjectsViceVersa.geterrormsgs(results);
        }
    }
    
    /*
* @ Method Name : createaccountrecords
* @ Description : This method is used to show the debug messages .
* @ Parameters:
* @Param Name :lstacc
* @ Returns : N/A
* @ Throws : NA
* @ References : Autocontactupdation and acccount creation
* @ Version : 1.0
*/
    public static void createaccountrecords(list<contact> lstcontacts)
    {
        
        list<contact> triggercons=lstcontacts;
        list<contact> lstcons = new list<contact>();
        if(!lstcontacts.isempty())
        {
            // to store the new account records
            list<account> lstacc= new list <account> ();
            for(contact con : triggercons)
            {
                Account acc = new Account ();
                acc.Name=con.LastName+'account';
                acc.Description=con.Description;
                
                lstacc.add(acc);
                //Contact Con2 = triggercons.get(triggercons.indexof(con));
                //System.debug('The Contact record from index method' + COn2);
                //con2.AccountId=acc.id;
                //con.AccountId=acc.id;
                // lstcons.add(con2); 
                
            } 
            list<id> accids= new list<id> ();
            if(!lstacc.isempty())
            {
                database.SaveResult[] results = database.insert(lstacc,false);
                // To display error messages in the debug file
                //recordsCreationbtntwoobjectsViceVersa.geterrormsgs(results);
                for(database.SaveResult res: results)
            {
                if(res.issuccess())
                {
                    system.debug('the records created ' + res.getid());
                    accids.add(res.getid());
                    
                } else 
                {
                    for(database.Error err : res.geterrors())
                    {
                        system.debug('the error records'+ err.getMessage());
                        system.debug('The error code is ' + err.getStatusCode());
                        system.debug('The error fields is ' + err.getFields());
                    }
                }
            }
                
                /*for(contact conss:triggercons)
                {
                    
                    for(id acc:accids )
                    {
                        conss.AccountId=acc;
                        lstcons.add(conss);
                    }
                }*/
                //database.SaveResult  [] conresutls = database.update(lstcons);
               // recordsCreationbtntwoobjectsViceVersa.geterrormsgs(conresutls);
                
                for(integer i=0;i<triggercons.size();i++)
                {
                    contact cont =triggercons[i];
                    cont.AccountId=accids[i];
                }
                
            }
            
            
            
            
        }
    }
    
 public static void contactrecordupdation(map<id, Contact> mapcontacts)
 {
     set<id> contactids= mapcontacts.keyset();
     list<account> accountrecords = new list<account> ();
     for(contact lds : mapcontacts.values())
     {
            Account acc  = new Account(Id = lds.AccountId);
         acc.name=lds.LastName;
         acc.Description=lds.Description;
        accountrecords.add(acc);
     }
     
     Database.SaveResult[] results =database.update(accountrecords);
     recordsCreationbtntwoobjectsViceVersa.geterrormsgs(results);
 }
    
 public static void accountrecordupdation (map <id,account> mapaccount)  
 {
     list<contact> updatedcontacts = new list<contact> ();
     for(Contact con: [select id,name,accountid,description from contact where accountid in :mapaccount.keyset() ])
     {
         id accid= con.AccountId;
         system.debug('the account id is '+ mapaccount.get(accid).name );
         con.lastname=mapaccount.get(accid).name;
         con.Description=mapaccount.get(accid).description;
         updatedcontacts.add(con);
     }
     
     Database.SaveResult[] results =database.update(updatedcontacts);
     recordsCreationbtntwoobjectsViceVersa.geterrormsgs(results);
     
 }
    
}

OBJECT2::_
trigger recordsCreationbtntwoobjectsViceVersaHelper2 on Contact (after insert,after update,before insert) {
    
    if(trigger.isinsert && trigger.isbefore)
    {
        
        if(recordsCreationbtntwoobjectsViceVersa.firstRun==true)
        {
            recordsCreationbtntwoobjectsViceVersa.firstRun=false;
           recordsCreationbtntwoobjectsViceVersa.createaccountrecords(trigger.new);
        }
       }
    if(trigger.isupdate &&     trigger.isafter)
    {
        if(recordsCreationbtntwoobjectsViceVersa.firstRun==true)
        {
            recordsCreationbtntwoobjectsViceVersa.firstRun=false;
           recordsCreationbtntwoobjectsViceVersa.contactrecordupdation(trigger.newmap);
        }
    }
    

}

OBJECT1::-
trigger recordsCreationbtntwoobjectsViceVersaHelper1 on Account (After insert,after update) {
    
    
    if(trigger.isInsert && trigger.isAfter)
    {
        if(recordsCreationbtntwoobjectsViceVersa.firstRun==true){
            recordsCreationbtntwoobjectsViceVersa.firstRun=false;
            recordsCreationbtntwoobjectsViceVersa.createcontactrecords(trigger.new);
        }
        
    }
    if(trigger.isupdate && trigger.isAfter)
    {
        if(recordsCreationbtntwoobjectsViceVersa.firstRun==true){
            recordsCreationbtntwoobjectsViceVersa.firstRun=false;
            recordsCreationbtntwoobjectsViceVersa.accountrecordupdation(trigger.newmap);
        }
        
    }

}