Salesforce clone utility class

Do you ever wonder to clone an object, if yes then I have an utility which works for every object. 

Public class MyCloneClass{
    //Pass the parameters as 1. Parent Object API Name, 2. Source record id, 3. API Name of the related field, 4. Child Object API Name
	Public static Sobject myCloneMethod(String objName, String recId, String parentFieldApiName, String childObjName){
        string qryStr = prepareQuery(objName, 'Id', recId);
        Sobject sobj = database.query(qryStr);
        Sobject clonedSObj = sobj.clone(false, true);
        insert clonedSObj;
        if(childObjName != null && parentFieldApiName != null){
            string childQry = prepareQuery(childObjName, parentFieldApiName, recId);
            List<Sobject> sobjList = database.query(childQry);
            List<Sobject> clonedSobjList = sobjList.deepClone(false);
            for(Sobject s : clonedSobjList)
                s.put(parentFieldApiName,;//Changing the parent id
            insert clonedSobjList;
        return clonedSObj;
    //This method is used to prepare the desired query string by passing the objectname and where clause condition
    private static String prepareQuery(String sobjName, String fieldName, String recId){
        Map<String, Schema.SObjectField> fieldsMap = Schema.getGlobalDescribe().get(sobjName.toLowerCase()).getDescribe().Fields.getMap();
        String fields = '';
        for(Schema.SObjectField sf : fieldsMap.values()) {
            Schema.DescribeFieldResult fr = sf.getDescribe();
                fields += fr.getName()+',';
            fields = fields.substring(0,fields.lastIndexOf(','));
        String qryString = 'Select ' +fields+' from '+sobjName+' where '+fieldName+' = \''+recId+'\'';
        return qryString;

Usage of this code:

//To clone a single account
MyCloneClass.myCloneMethod(Account, '001U0000003NoYY', null, null);
//To clone a account and their related contacts
MyCloneClass.myCloneMethod(Account, '001U0000003NoYY', 'AccountId', Contact);

You can call this class from a custom button/visualforce page/apex class. Happy coding…

This entry was posted in Apex, salesforce, Salesforce Tips & Tricks, Visualforce and tagged , , , . Bookmark the permalink.

One Response to Salesforce clone utility class

  1. Venkat Meka says:

    Superdb raaa :Venkat Meka

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s