apexsalesforce-lightning

In salesforce, how to create two sync Objects having similar fields


How to Create two Objects say Obj1 and Obj2 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 Obj1 should reflect in the Obj2 and vice versa.


Solution

  • Create both objects obj1 and obj2 with similar fields. Now create Apex trigger on both objects with after insert and after update event as shown below.

    trigger Obj1Trigger on obj1__c (after insert, after update) {
        list<obj2__c> recList = new list<obj2__c>();
        if(trigger.isAfter){
            
            if(trigger.isInsert || trigger.isUpdate){
                
                for(obj1__c ob : Trigger.new){
                    obj2__c obj2Rec = new obj2__c();
                    obj2Rec.name = ob.name;
                    obj2Rec.field1 = ob.field1;
                    obj2Rec.field2 = ob.field2;
                    obj2Rec.field3 = ob.field3;
                    recList.add(obj2Rec);
                }
            }
        }
    }
    

    Similarly create trigger for obj2.

    You will also need a way to associate two object's records with each other. There are two ways to associate the related records.

    way1:

    way2: