- Create an "
after insert
" trigger on Object1. This trigger will perform "insert" operation on Object2. The purpose of Field Set in this case must be to group fields that are supposed to be copied over.
- Build a Dynamic Query using fields defined in FieldSet1 from Object 1. Use
Database.query('YOUR_DYNAMIC_QUERY')
to fetch relevant records.
- Create instances of Object2 by looping over records obtained from Object1. To me it looks like, you do not really need a FieldSet2. However, if you still have a very hard requirement, then you will have to dynamically put field values using
sObject
class. You can retrieve fields from FieldSet2 as described here and use put
method in sObject
class. Sorry, I don't have an exact code.
However, I believe using a List Custom Setting to maintain map of both object fields should be easier. Using this technique ensures you have a configurable map. When you use field set approach, fields to be mapped between both objects is an additional step. This requirement mostly requires you to write dynamic apex code.
How to fetch records from Object1 using fields defined in a Field Set:
String query = 'SELECT ';
for (FieldSetMember fm: Schema.SObjectType.Object1__c.fieldSets.getMap().get('YOUR_FIELDSET_NAME').getFields()) {
query += f.getFieldPath() + ', ';
}
query += 'Id FROM Object1__c';
Object1__c[] records = Database.Query(query);
//Instantiate your Object2 here, get fields from FieldSet2 and put fieldName accordingly
Object2__c obj2 = new Object2__c();
obj2.put('fieldName','value');
sObject class
FieldSet class