• WHO WE ARE
  • WHAT WE DO
    • Salesforce
      • Implementations
        • Sales Cloud
        • Service Cloud
        • CPQ
        • Field Service Lightning
        • Field Service for SMEs
      • Developments
        • Salesforce Customization
        • Custom Application Development
        • AppExchange Product Development
      • Migrations
        • Classic to Lightning Migration
        • Other Systems to Salesforce Migration
      • Integrations
    • Data Science
      • BI Solutions
      • AI/ML solutions
      • Agentic AI
  • HOW WE DO
    • Delivery Model
    • Our Works
  • REACH US
    • Contact Us
    • Careers
  • BLOG
    • WHO WE ARE
    • WHAT WE DO
      • Salesforce
        • Implementations
          • Sales Cloud
          • Service Cloud
          • CPQ
          • Field Service Lightning
          • Field Service for SMEs
        • Developments
          • Salesforce Customization
          • Custom Application Development
          • AppExchange Product Development
        • Migrations
          • Classic to Lightning Migration
          • Other Systems to Salesforce Migration
        • Integrations
      • Data Science
        • BI Solutions
        • AI/ML solutions
        • Agentic AI
    • HOW WE DO
      • Delivery Model
      • Our Works
    • REACH US
      • Contact Us
      • Careers
    • BLOG
  • [email protected]
  • (+91) 44-49521562
Merfantz - Salesforce Solutions for SMEs
Merfantz - Salesforce Solutions for SMEs
  • WHO WE ARE
  • WHAT WE DO
    • Salesforce
      • Implementations
        • Sales Cloud
        • Service Cloud
        • CPQ
        • Field Service Lightning
        • Field Service for SMEs
      • Developments
        • Salesforce Customization
        • Custom Application Development
        • AppExchange Product Development
      • Migrations
        • Classic to Lightning Migration
        • Other Systems to Salesforce Migration
      • Integrations
    • Data Science
      • BI Solutions
      • AI/ML solutions
      • Agentic AI
  • HOW WE DO
    • Delivery Model
    • Our Works
  • REACH US
    • Contact Us
    • Careers
  • BLOG

How to Clone the Object Dynamically with All Fields in Salesforce

  • July 27, 2017
  • Merfantz Editor
  • Salesforce Developments Tutorial
  • 0

We already have the function deep clone to clone the fields. It has been done via SOQL query(i.e selected fields only cloned).

We need a dynamic clone of the objects without querying the field. Please refer the below

public class DynamicClone {
   public static List<sObject> cloneObjects(List<sObject> sObjects,
                                        Schema.SObjectType objectType){    
    // A list of IDs representing the objects to clone
    List<Id> sObjectIds = new List<Id>{};
    // A list of fields for the sObject being cloned
    List<String> sObjectFields = new List<String>{};
    // A list of new cloned sObjects
    List<sObject> clonedSObjects = new List<sObject>{};    
    // Get all the fields from the selected object type using 
    // the get describe method on the object type.
    if(objectType != null){
      sObjectFields.addAll(
        objectType.getDescribe().fields.getMap().keySet());
    }    
    // If there are no objects sent into the method, 
    // then return an empty list
    if (sObjects != null && 
        !sObjects.isEmpty() && 
        !sObjectFields.isEmpty()){    
      // Strip down the objects to just a list of Ids.
      for (sObject objectInstance: sObjects){
        sObjectIds.add(objectInstance.Id);
      }
      /* Using the list of sObject IDs and the object type, 
         we can construct a string based SOQL query 
         to retrieve the field values of all the objects.*/    
      String allSObjectFieldsQuery = 'SELECT ' + sObjectFields.get(0);     
      for (Integer i=1 ; i < sObjectFields.size() ; i++){
        allSObjectFieldsQuery += ', ' + sObjectFields.get(i);
      }    
      allSObjectFieldsQuery+='FROM'+objectType.getDescribe().getName()+ 
                               'WHERE ID IN (\''+sObjectIds.get(0)+ 
                               '\'';
      for (Integer i=1 ; i < sObjectIds.size() ; i++){
        allSObjectFieldsQuery += ', \'' + sObjectIds.get(i) + '\'';
      }    
      allSObjectFieldsQuery += ')';    
      try{      
        // Execute the query. For every result returned, 
        // use the clone method on the generic sObject 
        // and add to the collection of cloned objects
        for (SObject sObjectFromDatabase:
             Database.query(allSObjectFieldsQuery)){
          clonedSObjects.add(sObjectFromDatabase.clone(false,true));  
        }    
      } catch (exception e){
        // Write exception capture method 
        // relevant to your organisation. 
        // Debug message, Apex page message or 
        // generated email are all recommended options.
      }
    }      
    // return the cloned sObject collection.
    return clonedSObjects;
  }
}

An example of how you would call this method  to clone an Opportunity object from another Apex controller is:

Account ExisitingOpportunity= [select Id from Opportunity where 
                                 id=:ApexPages.currentPage().getParameters().get('id')]; sObject originalSObject = (sObject)ExisitingOpportunity; List<sObject> originalSObjects = new List<sObject>{originalSObject}; List<sObject> clonedSObjects =DynamicClone .cloneObjects( originalSobjects, originalSobject.getsObjectType()); Opportunity clonedOpportunity = (Opportunity)clonedSObjects.get(0);

We are the ISV Partners and Please reach us for custom development => www.merfantz.com

------------------------Thank You-------------------------

Author Bio

Merfantz Editor
+ Recent Posts
  • August 4, 2023
    How to Setup CRM Analytics for Financial Services Cloud
  • August 2, 2023
    How to Get Started with Salesforce Hyperforce - Merfantz
  • July 28, 2023
    Health Cloud Mastery: Salesforce Trailhead for Effective Healthcare CRM
  • July 26, 2023
    How to integrate Data cloud and Marketing cloud In Salesforce
Tags: Field Service ManagementFieldax
  • Previous Weekday and Weekend Calculation Using Formula Field in Salesforce
  • Next How to Create Buttons Using Formula field in Salesforce

Leave a Reply

You must be logged in to post a comment.

Merfantz Technologies is a leading Salesforce consulting firm dedicated to helping small and medium enterprises transform their operations and achieve their goals through the use of the Salesforce platform. Contact us today to learn more about our services and how we can help your business thrive.

Discover More

Terms and Conditions
Privacy Policy
Cancellation & Refund Policy

Contact Info

  • No 96, 2nd Floor, Greeta Tech Park, VSI Industrial Estate, Perungudi, Chennai 600 096, Tamil Nadu, INDIA
  • (+91) 44-49521562
  • [email protected]
  • 9:30 IST - 18:30 IST

Latest Posts

Comprehensive Overview of Salesforce Agent-Force Platform
Comprehensive Overview of Salesforce Agent-Force Platform June 12, 2025
Salesforce GraphQL Revolutionizing Data Queries in CRM
Salesforce GraphQL: Revolutionizing Data Queries in CRM June 6, 2025
Unlocking the Power of Dynamic Forms in Salesforce Lightning App Builder
Unlocking the Power of Dynamic Forms in Salesforce Lightning App Builder May 29, 2025

Copyright @2023 Merfantz Technologies, All rights reserved