The use case is when a record on Object1 is created, I want to create a new record on Object2 from code(trigger). For this, I am supposed to use fieldSet.

Till now, I have created 2 fieldsets on both the objects, now I need to copy data from fields of fieldSet1 (of Object1) to FieldSet2 (Of Object 2) and create a new record out of it on the object2.

Kindly suggest workaround

1 Answer 1

  1. 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.
  2. Build a Dynamic Query using fields defined in FieldSet1 from Object 1. Use Database.query('YOUR_DYNAMIC_QUERY') to fetch relevant records.
  3. 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(); 

sObject class

FieldSet class

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .