Clone Record By Apex in Salesforce

by Rijwan Mohmmed
0 comment
clone-record-by-apex-in-salesforce-techdicer

Hello friends, today we are going to discuss How to Clone Record By Apex in Salesforce. In Salesforce Apex there is a method called clone() which creates a copy of the sObject record. This method has four Boolean-type optional parameters.

Also check this : Refresh Standard Components in LWC Salesforce

Clone Method

clone(preserveId, isDeepClone, preserveReadonlyTimestamps, preserveAutonumber)

Parameters :

  1. opt_preserve_id : Determines whether the ID of the original object is preserved or cleared in the duplicate. If we set to true, the ID is copied to the duplicate. The default is false, that is, the ID is cleared.
  2. 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.
  3. 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.
  4. 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.

Code :

cloneRecordCtrl.cls: In this class, we do Clone Record By Apex in Salesforce. So we create a new record.

public class cloneRecordCtrl{
	
	public static void cloneRecord(){
		// retrive contact record for clone
		Contact con = [SELECT FirstName, Email, LastName FROM Contact LIMIT 1];
		// clone record
		Contact conCopy = con.clone(false, false, false, false);
		insert conCopy;
	}
}


Output:

Reference :

  1. Salesforce Apex

You may also like

Leave a Comment