-3

I want to clone an existing account record. Is it possible using .clone in apex code? I need the data to be copied too.

I have an existing account(A) with values, when the user changes a particular field i want to create another account record(B) and copy all the values from A to B excluding the child records. Is this possible using Clone method? When tried using the clone method, i still had to give the name of the account, and none of the fields where copied, Can anyone help on this?

  • 2
    Can you be more clear about what you have tried and where you are stuck? As your question is written, the answer seems to be an obvious yes. – Adrian Larson Jun 23 '17 at 22:15
  • I have an existing account(A) with values, when the user changes a particular field i want to create another account record(B) and copy all the values from A to B excluding the child records. Is this possible using Clone method? When tried using the clone method, i still had to give the name of the account, and none of the fields where copied, Can anyone help on this? – sunshine Jun 24 '17 at 13:22
0

It does not appear that there is a standard way to clone an sObject without cloning its relationship fields. You can use the deepClone parameter to specify that you want the relationship objects to be cloned as well rather than just the reference, but they are still present on the object.

You could define a custom method to do this:

public void noRelationClone(sObject record, boolean preserveID, 
                            boolean preserveReadOnlyTimestamps, boolean preserveAutonumber)
{
    sObject recordClone = record.clone(preserveID, false, 
                                       preserveReadOnlyTimestamps, preserveAutoNumber);
    for(Schema.sObjectField field : recordClone.getSObjectType().getDescribe()
                                                                .fields.getMap().values())
    {
        if (field.getDescribe().getType() == Schema.DisplayType.Reference)
        {
            recordClone.put(field, null);
        }
    }
    return recordClone;
}

Note that I haven't tested the above.

  • i had to query the record before cloning, that what i was missing. Thanks for the code illusiveBrian. – sunshine Jun 29 '17 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.