0

I have below execute method of an apex batch class where I need to clone Question_Response_vod__c records of existing with changes in few fields. Can someone please guide me here. I have in code to create but not getting how to clone.

Apex Class snippet

List<Question_Response_vod__c> s2q1rListToInsert = new List<Question_Response_vod__c>();
    for(Question_Response_vod__c s1q1r : [Select Id,Survey_Question_vod__c,Text_vod__c from Question_Response_vod__c where Survey_Question_vod__c in : s1qlist])
    {

        s2q1rListToInsert.add(new Question_Response_vod__c(Survey_Question_vod__c=s1qs2qMap.get(s1q1r.Survey_Question_vod__c),Text_vod__c=s1q1r.Text_vod__c));  // Need to clone with changes in mentioned fields.
    }

    If(s2q1rListToInsert.size()>0)  
         Insert s2q1rListToInsert;
3
  • do you want to clone s2q1rListToInsert list? or s1q1r ?
    – Ratan Paul
    Commented May 5, 2016 at 7:16
  • I need s1q1r to be cloned with changes in Survey_Question_vod__c and text_vod__c as here - Survey_Question_vod__c=s1qs2qMap.get(s1q1r.Survey_Question_vod__c),Text_vod__c=s1q1r.Text_vod__c) Commented May 5, 2016 at 7:18
  • then you need to query all the fields in soql else it will not copy all the fields to new record
    – Ratan Paul
    Commented May 5, 2016 at 7:26

1 Answer 1

1

You can update your code to this:

List<Question_Response_vod__c> s2q1rListToInsert = new  List<Question_Response_vod__c>();
for(Question_Response_vod__c s1q1r : [Select Id,Survey_Question_vod__c,Text_vod__c from Question_Response_vod__c where Survey_Question_vod__c in : s1qlist])
{
    Question_Response_vod__c clonedRecord = s1q1r.clone();
    clonedRecord.Survey_Question_vod__c = /*New value here*/;
    clonedRecord.Text_vod__c = /*New value here*/;
    s2q1rListToInsert.add(clonedRecord);
}

Here, a new instance is created by cloning the current record in iteration, then change the value of the fields as per requirement and then add this record to the list to be inserted.

3
  • 1
    one small issue here.. OP need to query all the field then only using clone all the fields will be copy to new record.
    – Ratan Paul
    Commented May 5, 2016 at 7:34
  • Yes. I forgot to mention that. @SFDC_Learner Please note that only the fields which are queried are cloned when using sobject.clone() method.
    – ajinkyah
    Commented May 5, 2016 at 7:36
  • Yes but still it retains old value. :( Commented May 6, 2016 at 14:54

You must log in to answer this question.

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