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
Shivkumar SheteShivkumar Shete 

Dynamically copy field values from one custom object to another

NagendraNagendra (Salesforce Developers) 
Hi Shiva,
trigger DupeData on CO1__c( after insert, after update ) {
  Set<String> fields = CO1__c.getDescribe().fields.getMap().keySet();
  Map<Id,CO2__c> co2 = new Map<Id,CO2__c>();
  for(CO1__c record: Trigger.new) {
    co2.put(record.co2__c,new co2__c(id=record.co2__c));
    for(String field:fields) {
      if(field.indexOf('__c')>-1) { // This is a custom field.
        try {
          co2.get(record.co2__c).put(field,record.get(field));
        } catch(exception e) { /* NOTE: This just means copy failed. */ }
      }
    }
  }
  update co2.values();
}
This is an approximate means of copying the data. You could also provide a blacklist instead of just checking for a custom field. Field names are for example purposes only, but the mechanism is sound. You could also use a query if you may have more than one child per parent; a similar flow would result, but you could simply use a list instead of a map since the query would return each related record exactly once.
 
Edit: The "copy failed" just applies to the single field that was being attempted. Either the destination field did not exist, had an incompatible data type, or was read-only (e.g. a formula field). The records themselves would still be copied, minus the fields that failed to copy.

For more information please check with below link. Hope this helps.

Kindly mark this as solved if the reply was helpful.

Thanks,
Nagendra