+ Start a Discussion
csreddy7799csreddy7799 

Cloning record in wrapper class

I have created one wrapper class with sObject and index for sObject and am getting and setting list of wrapper to show on VF page. On VF page im showing some fields from that sObject and provided one button to clone that record so that cloned record  will be shown on next row. In the controller if i assign values directly from wrapper (i.e. new wrapper instance = wrapper instance to be clone) its getting cloned and displayed on VF but while saving its giving me error as "id" of sObject is also get clonned. If i try to get field values one by one from wrapper its giving me null values. (eg new wrapper.sObject.field = wrapperToBeCloned.sObject.field), sObject from the wrapper to be cloned is giving null values. How to solve this problem ?

 

Here are two possibilities as below when i clicked on clone button in vf page

 

1.  JobSuite__job__c obj = new JobSUite__Job__c();
     obj.Name = '';
     obj.JobSuite__Job_Description__c = wrapJob.objJob.JobSuite__Job_Description__c;
     obj.JobSuite__Dummy_Picklist_2__c = wrapJob.objJob.JobSuite__Dummy_Picklist_2__c;
     jbw.objJob = obj;
     wrapper.add(jbw)

If i use above code the record is assigned by blank values.

if i print wrapJob.objJob, it is displaying null in system.debug.

 

But when i used below code record is getting cloned and displayed in vf page 

 

 

    here am copying record from previous wrapper record
     jbw.objJob = wrapJob.objJob;
     wrapper.add(jbw)

 

 If i use above code the record is copied but while saving it is throwing exception because of same record ID.

 

Sean TanSean Tan

The reason you'll get the duplicate Id error is because when you do the assignment like so:

 

jbw.objJob = wrapJob.objJob;

 

Is because all you're doing is assigning the memory pointer reference, meaning it's just the exact same instance of your object, any changes made in the above initial row will propagate to the second row and vice versa. I'm not going to go how into memory references work so you'll have to do your own research on it.

 

Now in terms on how you can clone the object, you can use the SObject clone() method.

 

See here:

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_sobject.htm?SearchType=Stem&Highlight=clone|cloning|cloned|Clone

 

Specifically the clone method.

 

An implementation would be something as simple as this:

 

//First parameter = preserve Id which you don't want
//Second parameter = deep clone, meaning a fresh new object rather than just a pointer so changes to the initial record won't affect the new one and vice versa
jbw.objJob = wrapJob.objJob.clone(false, true);

 

csreddy7799csreddy7799

Hi Tan,

 

 I have laready tried Clone(false, true). Here if use clone, in vf page on click of Duplicate  button am getting new row with blank values only.