function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SyracuseSnowSyracuseSnow 

Apex code clone feature

Can anyone tell me how to create a replica of a SObject using Apex code? For example, when a opportunity is saved, if certain conditions apply, we would like a clone of this opportunity created as a child opportunity to the current one.

I have been trying using sobject.clone() method, but it seems to be designed for a different purpose, and only creates a new pointer, which is not what I am looking for.

Your help is highly appreciated.

mtbclimbermtbclimber
Does this not work for what you are looking to do?

Code:
trigger cloneAccount on Account (after update) {
   List<Account> accountList = new List<Account>();
   for(Account a:Trigger.new) {
      accountList.add(a.clone(false));
   }

   insert accountList;
}

 

 

SyracuseSnowSyracuseSnow
Thanks, Andrew. This is certainly helpful, except when I tried to run the similar logic & basically the same code for cloning a case upon saving it, I got the following error message:

"First exception on row 0; first error: INVALID_FIELD_FOR_INSERT_UPDATE, Case: bad field names on insert/update call: IsSelfClosed, IsVisibleInCss: [IsSelfClosed, IsVisibleInCss]: Trigger.AutoCreateSubCase: line 9, column 5"

I don't see these two fields, isSelfClosed and IsVisibleInCss. Not quite sure what I should do.

Thanks,
Pat McQueenPat McQueen

Can you post your code that is not working? 

pat

SyracuseSnowSyracuseSnow
Yes, Pat. Please see the code below:

trigger AutoCreateSubCase on Case (after update) {
    List<Case> listCases = new List<Case>();
    for(Case c: Trigger.new) {
        Case newChildCase = c.clone(false);
        newChildCase.ParentId = c.ID;
        listCases.add(newChildCase);
    }
    insert listCases;
}   


Pat McQueenPat McQueen
Hello - This is most likely a bug.  For now you can just null out those two fields in the cloned object so the create ignores them.