Clone Any SObject Record With Lightning Component

In this blog, I am going to show how to clone the record using lightning component quick action. The same functionality can be implemented by using even quick actions without having component also. But this component will be used to clone any object single record.

Step 1: Lightning Component 

Here is the complete code for the quick action.

Apex Class

public class CloneSingleRecord {
    @AuraEnabled
    public static String cloneAnySobjet(String recordId){
        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        String objectAPIName = '';
        String keyPrefix = recordId.substring(0,3);
        for( Schema.SObjectType obj : schemaMap.Values() ){
            String prefix = obj.getDescribe().getKeyPrefix();
            if(prefix == keyPrefix){
                objectAPIName = obj.getDescribe().getName();
                break;
            }
        }
        Set <String> fieldMap = schemaMap.get(objectAPIName).getDescribe().fields.getMap().keySet();
        String soqlQuery = 'SELECT ' ; 
        for (String s :fieldMap ){
            if(schema.getGlobalDescribe().get(objectAPIName).getDescribe().fields.getMap().get(s).getDescribe().isAccessible()){
                soqlQuery +=  + s+',';
            }
        }
        soqlQuery =  soqlQuery.removeEnd(',');
        soqlQuery += ' FROM ' +objectAPIName +' WHERE ID = \'' + recordId +'\'' ;
        System.debug('soqlQuery'+soqlQuery);
        SObject record = Database.query(soqlQuery);
        SObject clondedParentRecordID= record.clone(false, false, false, false);
        try{
            insert clondedParentRecordID ;
            return clondedParentRecordID.id ;
        }catch(Exception e){
            return '' ;
        }
        
    }
}

Lightning Component

<aura:component implements="force:lightningQuickActionWithoutHeader,force:hasRecordId" controller="CloneSingleRecord">
    <aura:attribute name="errorMsg" type="String" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <ui:message aura:id="errorMsg" severity="error" class="slds-hide">
        {!v.errorMsg}
    </ui:message>
    
</aura:component>
({
    doInit : function(component, event, helper) {
        var action = component.get("c.cloneAnySobjet");
        action.setParams({"recordId": component.get("v.recordId")});
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === "SUCCESS") {
                var sObjectEvent = $A.get("e.force:navigateToSObject");
                sObjectEvent.setParams({
                    "recordId": response.getReturnValue(),
                    "slideDevName": "detail"
                });
                sObjectEvent.fire();
            }else if (state === "ERROR"){
                var errors = response.getError();
                if(errors) {
                    cmp.set("v.errorMsg", errors[0].message);
                    var errorMsg = cmp.find('errorMsg');
                    $A.util.removeClass(errorMsg, 'slds-hide');
                    var field = cmp.find('field');
                    $A.util.addClass(field, 'slds-hide');
                }
            }
        });
        $A.enqueueAction(action);
    },
})

Step 2: Create a Quick Action

now create a new quick action as shown below

Step 3: Add the Action to the page layout

Now add the quick action to the page layout Salesforce Mobile and Lightning Experience Actions section. After adding the quick action, you can able to see them on the page layout.

Testing 

Now when you click on the Custom clone button it is going to clone the record.