[SalesForce] Clone sObject field values from Wrapper class

I have created one wrapper class with sObject and index for sObject and im 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 it will be shown on next row.
At 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 ?

Best Answer

I think you need to clone an sObject first, and then add it to a new instane of the wrapper. I've created a simple example page and controlle where the wrapper records could be cloned:

Page:

<apex:page controller="test1">
<apex:form>
<apex:pageBlock>

    List 1
    <apex:pageBlockTable value="{!wrapperList}" var="w">
        <apex:column>
            <apex:commandButton action="{!cloneWrappeer}" reRender="clones" value="clone"/>
        </apex:column>
        <apex:column value="{!w.index}"/>
        <apex:column value="{!w.acc.Street__c}"/>
    </apex:pageBlockTable>

    <br/>

    Clones
    <apex:pageBlockTable value="{!wrapperClonedList}" var="w" id="clones">
        <apex:column value="{!w.index}"/>
        <apex:column value="{!w.acc.Street__c}"/>
    </apex:pageBlockTable>

</apex:pageBlock>
</apex:form>
</apex:page>

Controller:

public with sharing class test1 {
    public List<MyWrapper> wrapperList { get; set; }
    public List<MyWrapper> wrapperClonedList { get; set; }

    public class MyWrapper{
        public String index { get; set; }
        public Account acc { get; set; }

        public MyWrapper(Account a){
            this.acc = a;
            this.index = a.name;
        }
    }

    public void cloneWrappeer(){
        Account a = wrapperList[0].acc.clone(false, true, false, false);
        wrapperClonedList.add(new MyWrapper(a));
    }

    public test1() {
        wrapperList = new List<MyWrapper>();
        wrapperClonedList = new List<MyWrapper>();
        testacc = [select id, name, Street__c from account limit 1];
        wrapperList.add(new MyWrapper(testacc));
    }
}

The result page:

enter image description here

Related Topic