+ Start a Discussion

Copy/ clone one object record to another object.



I am having two object called objectA and objectB and both having same set of fields. Now I want to copy the objectA record to objectB periodically or on save of objectA record. Is there any solution to achieve this scenario. I thought of doing it in trigger, but I am have 100+ fields!.

Prafull G.Prafull G.
You are thingking in the correct direction. There is no other way that Apex Code to copy records from one object to other object.
However to simplify or limit the code you can choose different approach i.e. instead of writing all 100+ fields in apex trigger, use Custom setting to store these fields and then use sObject get() and set() methods do the data copy stuff.

Hope this helps!

Hi Thanks.


 Regarding the custom settings, do i need to create custom setting with all the field which is available in my objectA and enterdata?

Prafull G.Prafull G.
No, You do not need to create custom setting for each field.

As custom setting is like an object you can create 2 custom fields on that and then create records 100+ in the custom setting to populate the field API Names.
For Example:
List type custom setting: Copy Values (Copy_Values__c)
Custom Fields:
Source Field Name (Source_Field_Name)
Dest Field Name (Dest_Field_Name)

Then you have to click on manage button and insert record to this custom setting. lets say you have fields as Source_A__c, Source_B__c etc and have to copy to Dest_A__c, Dest_B__c etc.
then you have to create records in custom setting.. one for each pair.

Once you done with this configuration then you have to write code in your trigger to create map of source field name to destination field name.

Hope this helps.

Theoretically, you could use Describe info to dynamically go through the object in question and generate a new object of the second type without having to hard code field names anywhere. Depending on the use case, it may be much easier to maintain if changes will be made to the objects in the future.

om gupta(sfdc)om gupta(sfdc)
hi i have done some experiment and it worked lets hope you will also get success
there are two object import_shipment__c and house__c 

Import_Shipment__c shipment = new Import_Shipment__c();
shipment.Pieces__c = 1;
String json1 = JSON.serialize(shipment);


House__c house = (House__c)System.JSON.deserialize(json1,House__c.class); 

om gupta