9

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?

2
  • Why do you feel the need to clone every field?
    – Adrian Larson
    Commented Sep 30, 2016 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
    Commented Sep 30, 2016 at 21:26

2 Answers 2

22

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(...);
}
2

Late to the party but you could use something like this as well.

String fieldsNames = '';
for (Schema.SObjectField sObjectField : Schema.getGlobalDescribe().get('MyCustomObject__c').getDescribe().fields.getMap().values()) {
     fieldsNames += sObjectField.getDescribe().getName() + ',';
}
Database.query(
      'SELECT ' + fieldsNames + ' FROM MyCustomObject__c Where Age = 20'
);

And probably you would have to filter some fields, as not all of them are suitable for cloning;

You must log in to answer this question.

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