5

I am trying to clone the records of a custom object. I know that I can use the deepClone() method of the List class to do this.

List<MyCustomObject__c> originalList = [Select Id, Name, Age From MyCustomObject__c Where Age = '20'];

List<MyCustomObject__c> cloneList = originalList.deepClone();

My question here is I don't just want to clone the records with fields that I have in query (Name, Age) but I want the record to be cloned with all the fields that it has. For this do I need to put all the fields in my query or is there any other way to do this?

  • Why do you feel the need to clone every field? – Adrian Larson Sep 30 '16 at 21:24
  • @AdrianLarson So the object for which I am cloning records has many fields on it and I am not sure which specific fields we want on cloned records. So I don't want to miss out on any fields while doing the clone operation. Does that make sense ? – Yogesh D Sep 30 '16 at 21:26
16

Yes, deepClone will only pull in fields you have in memory. In this case, you do indeed have to query for them. You should question why you need every field, but if you want to maintain a configurable option, I recommend you use a Field Set. This will allow you some flexibility in which fields to copy, without forcing you to copy every single field.

public static List<MyObject__c> getClones(String age)
{
    List<String> fields = new List<String>();
    FieldSet fieldsToClone = SObjectType.MyObject__c.fieldSets.FieldsToClone;
    for (FieldSetMember field : fieldsToClone.getFields()) {
        fields.add(field.getFieldPath());
    }
    String soql = 'SELECT ' + String.join(fields, ',') +
        ' FROM MyObject__c WHERE Age__c = \'' + String.escapeSingleQuotes(age) + '\'';
    return Database.query(soql).deepClone(...);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.