How To Clone A Record Using Apex In Salesforce?

How To Clone A Record Using Apex In Salesforce?


In this blog, you will learn how you can clone a record using apex in salesforce.

Follow below simple steps
  • Go to Setup
  • Open Developer Console
  • Go To Debug menu
  • Select Open Execute Anonymous Window from dropdown

Account acc = [select id, name, phone, site, type, active__c from account limit 1];

account copyAcc = acc.clone(false,false,false,false);

insert copyAcc;

  • Click on Execute

Creating a copy of the sObject record.

clone(Boolean, Boolean, Boolean, Boolean):

Parameters (Type : Boolean) (Optional)

opt_preserve_id

Determines whether the ID of the original object is preserved or cleared in the duplicate.

If set to true, the ID is copied to the duplicate. 

The default is false, that is, the ID is cleared.


opt_IsDeepClone

Determines whether the method creates a full copy of the sObject field, or just a reference:
If set to true, the method creates a full copy of the sObject. 

All fields on the sObject are duplicated in memory, including relationship fields. Consequently, if you make changes to a field on the cloned sObject, the original sObject is not affected.

If set to false, the method performs a shallow copy of the sObject fields. 

All copied relationship fields reference the original sObjects. Consequently, if you make changes to a relationship field on the cloned sObject, the corresponding field on the original sObject is also affected, and vice-versa. The default is false.


opt_preserve_readonly_timestamps

Determines whether the read-only timestamp fields are preserved or cleared in the duplicate. If set to true, the read-only fields CreatedById, CreatedDate, LastModifiedById, and LastModifiedDate are copied to the duplicate. 

The default is false, that is, the values are cleared.


opt_preserve_autonumber

Determines whether auto number fields of the original object are preserved or cleared in the duplicate. If set to true, auto number fields are copied to the cloned object. 

The default is false, that is, auto number fields are cleared.


Demo

0 Comments