function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Mahesh Babu 187Mahesh Babu 187 

Deep Clone a Case Record with Related Lists

Hi Team,

I have a requirement to clone case records with it's related Open Activities(Task and Event), Case Comments, Emails and Attachments.
i have written a Apex class and created a VF Page. The VF page is called on a button click. But through my code only the record is getting cloned but it's related list items are not getting cloned.
I took help from below articles:

Help Link 1 (https://blog.jeffdouglas.com/2009/11/19/apex-deep-clone-controller/) :https://blog.jeffdouglas.com/2009/11/19/apex-deep-clone-controller/
Help Link-2 (https://developer.salesforce.com/forums/?id=906F0000000AbWJIA0) :https://developer.salesforce.com/forums/?id=906F0000000AbWJIA0

APEX CODE:

global with sharing class CaseCloneController {
    
    private final Id recordId;
    private final Case record;
    private final ApexPages.StandardController controller; 

    public CaseCloneController(ApexPages.StandardController controller) {
        this.controller = controller;
        this.record = (Case)(this.controller.getRecord());
        this.recordId = this.controller.getId();
        System.debug('this.recordId'+recordId); // it is retrieving null
    }    

    public PageReference cloneWithItems() {
        Case newCase = this.record.clone(false, true);
        System.debug('newCase'+newCase);
        insert newCase;

        List<Attachment> clonedAttachments = new List<Attachment>();
        for (Attachment attachment: [select ParentId, Body, BodyLength from Attachment where ParentId = :this.recordId]) {
            System.debug('attachment.ParentId'+attachment.ParentId);
            Attachment clonedAttachment = attachment.clone(false, true);
            clonedAttachment.ParentId = newCase.Id;
            clonedAttachments.add(clonedAttachment);
        }
        insert clonedAttachments;
        
        List<CaseComment> casecomments = new List<CaseComment>();
             for(CaseComment cc : [Select Id, ParentId, IsPublished, CommentBody, CreatedById, CreatedDate, SystemModstamp, LastModifiedDate, LastModifiedById, IsDeleted From CaseComment where ParentId=:this.recordId]){
                 CaseComment newcasecomment = cc.clone(false, true);
                 newcasecomment.ParentId = newCase.id;
                 casecomments.add(newcasecomment);
             }
             insert casecomments;
        
        List<Task> clonedTasks = new List<Task>();
        for(Task t : [Select id, WhatId, Subject, Status from Task where WhatId =:this.recordId]){
            Task newtask = t.clone(false, true);
            newtask.WhatId = newCase.id;
            clonedTasks.add(newtask);
        }
        insert clonedTasks;
        
        List<Event> clonedEvent = new List<Event>();
        for(Event e : [Select id, Location, Description, Type, WhatId from Event where WhatId =: this.recordId]){
            Event newevent = e.clone(false, true);
            newevent.WhatId = newCase.id;
            clonedEvent.add(newevent);
        }
        insert clonedEvent;
        
        List<EmailMessage> clonedEmail = new List<EmailMessage>();
        for(EmailMessage email : [Select id, ParentId, ActivityId, BccAddress, CcAddress, FromAddress, FromName, Subject, TextBody from EmailMessage where ParentId =: this.recordId]){
            EmailMessage newemail = email.clone(false, true);
            newemail.ParentId = newCase.id;
            clonedEmail.add(newemail);
        }
        insert clonedEmail;

        return new ApexPages.StandardController(newCase).view();
    }  
    
}

VISULAFORCE PAGE:

<apex:page standardController="Case" extensions="CaseCloneController" action="{!cloneWithItems}">
     <apex:pageMessages />
</apex:page>

Please help me in solving this issue.

Thank You,
Mahesh
ShirishaShirisha (Salesforce Developers) 
Hi Mahesh,

Greetings!

Here is the simple example to clone the record along with its related List in the below blog.

https://www.infallibletechie.com/2013/06/how-clone-record-with-related-records.html

Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri
Mahesh Babu 187Mahesh Babu 187
Hi Shirisha,

Thanks for your help. 
I have implemented this functionality. I am able to clone case with it's related list but I am facing an issue. 
While cloning the email messages, the attachments attached with the email are not getting cloned.
Please find my Apex code and guide me to make the change.

global with sharing class CaseCloneController {
    
    private final Id recordId;
    private final Case record;
    
    private final ApexPages.StandardController controller; 
    
    public CaseCloneController(ApexPages.StandardController controller) {
        this.controller = controller;
        this.record = (Case)(this.controller.getRecord());
        this.recordId = this.controller.getId();
        System.debug('this.recordId'+recordId);
    }    
    
    public PageReference cloneWithItems() {
      
        Case newCase = this.record.clone(false, true);  
        Case cd = [Select id, OTP__c, Escalation_Status__c, NCU_Block__c, NCU_Name__c, Task_Escalated__c, SPC_Name__c, Fault_Code__c, Origin,
                   Row_Location__c, Serial_Number__c, CASE_TYPE__c, Use_box_below_for_Additional_Details__c, ISSUE_TYPE__c,
                   Subject, ISSUE_SUB_TYPE__c, TECHNICAL_ISSUE__c, TECHNICAL_DETAILS__c, Comments, X1st_Escalation_Time__c,
                   X2nd_Escalation_Time__c, X3rd_Escalation_Time__c, X4th_Escalation_Time__c, 
                   Site_Id__c,  Case_Accepted_Time__c, Sites_ID__c, Client_Tier__c, Priority,
                   Shipping_Address__c, Same_as_Site_Address__c, 
                   Customer_Since__c, Project_no__c, Opportunity__c, Commissioning_Tech__c, Latitude__c, 
                   O_M_Company__c, Longitude__c, O_M_Tech__c, SQlite_version__c, O_M_Tech_email__c, TrackerCX__c, Connections__c, 
                   Owner_Contact__c, Network_Provider__c, Email2__c, NetWork_Provider_Contact__c, EPC_Company__c, Email1__c, EPC_Contact__c, Email3__c,
                   Description, Warranty__c, Warranty_Non_Standard_Warranty__c, Warranty_Trigger_Type__c, 
                   Warranty_On_Sun__c, Warranty_Start_Date__c, Warranty_Labor_Included__c, Warranty_Parts_Expiration_Date__c,
                   Warranty_Parts_Years__c, Warranty_Structural_Expiration_Date__c, Warranty_Structural_Years__c,
                   Warranty_Controller_Battery_Expiration__c, Warranty_Battery_Years__c, Warranty_Storage_Expiration_Date__c,
                   Warranty_Notes__c, Additional_Emails__c, Tracking_Number__c, SuppliedEmail, Make_this_my_case__c, Status, Reason,Issue_1__c,Issue_2__c,Issue_3__c,
                   Details_1__c,Details_2__c,Details_3__c,Quantity1__c,Quantity2__c,Quantity_3__c,Add_more_issues1__c,Add_more_issues2__c from Case where id =: this.recordId];
        
        newCase.OTP__c = cd.OTP__c;
        newCase.Escalation_Status__c = cd.Escalation_Status__c;
        newCase.NCU_Block__c = cd.NCU_Block__c;
        newCase.NCU_Name__c = cd.NCU_Name__c;
        newCase.Task_Escalated__c = cd.Task_Escalated__c;
        newCase.SPC_Name__c = cd.SPC_Name__c;
        newCase.Fault_Code__c = cd.Fault_Code__c;
        newCase.Row_Location__c = cd.Row_Location__c;
        newCase.Serial_Number__c = cd.Serial_Number__c;
        newCase.CASE_TYPE__c = cd.CASE_TYPE__c;
        newCase.Use_box_below_for_Additional_Details__c = cd.Use_box_below_for_Additional_Details__c;
        newCase.ISSUE_TYPE__c = cd.ISSUE_TYPE__c;
        newCase.Subject = cd.Subject;
        newCase.ISSUE_SUB_TYPE__c = cd.ISSUE_SUB_TYPE__c;
        newCase.TECHNICAL_ISSUE__c = cd.TECHNICAL_ISSUE__c;
        newCase.TECHNICAL_DETAILS__c = cd.TECHNICAL_DETAILS__c;
        newCase.Comments = cd.Comments;
        newCase.X1st_Escalation_Time__c = cd.X1st_Escalation_Time__c;
        newCase.X2nd_Escalation_Time__c = cd.X2nd_Escalation_Time__c;
        newCase.X3rd_Escalation_Time__c = cd.X3rd_Escalation_Time__c;
        newCase.X4th_Escalation_Time__c = cd.X4th_Escalation_Time__c;
        newCase.Site_Id__c = cd.Site_Id__c;
        newCase.Case_Accepted_Time__c = cd.Case_Accepted_Time__c;
        newCase.Sites_ID__c = cd.Sites_ID__c;
        newCase.Client_Tier__c = cd.Client_Tier__c;
        newCase.Priority = cd.Priority;
        newCase.Shipping_Address__c = cd.Shipping_Address__c;
        newCase.Same_as_Site_Address__c = cd.Same_as_Site_Address__c;
        newCase.Customer_Since__c = cd.Customer_Since__c;
        newCase.Project_no__c = cd.Project_no__c;
        newCase.Opportunity__c = cd.Opportunity__c;
        newCase.Commissioning_Tech__c = cd.Commissioning_Tech__c;
        newCase.Latitude__c = cd.Latitude__c;
        newCase.O_M_Company__c = cd.O_M_Company__c;
        newCase.Longitude__c = cd.Longitude__c;
        newCase.O_M_Tech__c = cd.O_M_Tech__c;
        newCase.SQlite_version__c = cd.SQlite_version__c;
        newCase.O_M_Tech_email__c = cd.O_M_Tech_email__c;
        newCase.TrackerCX__c = cd.TrackerCX__c;
        newCase.Connections__c = cd.Connections__c;
        newCase.Owner_Contact__c = cd.Owner_Contact__c;
        newCase.Network_Provider__c = cd.Network_Provider__c;
        newCase.Email2__c = cd.Email2__c;
        newCase.NetWork_Provider_Contact__c = cd.NetWork_Provider_Contact__c;
        newCase.Email1__c = cd.Email1__c;
        newCase.EPC_Contact__c = cd.EPC_Contact__c;
        newCase.Email3__c = cd.Email3__c;
        newCase.Description = cd.Description;
        newCase.Warranty__c = cd.Warranty__c;
        newCase.Warranty_Non_Standard_Warranty__c = cd.Warranty_Non_Standard_Warranty__c;
        newCase.Warranty_Trigger_Type__c = cd.Warranty_Trigger_Type__c;
        newCase.Warranty_On_Sun__c = cd.Warranty_On_Sun__c;
        newCase.Warranty_Start_Date__c = cd.Warranty_Start_Date__c;
        newCase.Warranty_Labor_Included__c = cd.Warranty_Labor_Included__c;
        newCase.Warranty_Parts_Expiration_Date__c = cd.Warranty_Parts_Expiration_Date__c;
        newCase.Warranty_Parts_Years__c = cd.Warranty_Parts_Years__c;
        newCase.Warranty_Structural_Expiration_Date__c = cd.Warranty_Structural_Expiration_Date__c;
        newCase.Warranty_Structural_Years__c = cd.Warranty_Structural_Years__c;
        newCase.Warranty_Controller_Battery_Expiration__c = cd.Warranty_Controller_Battery_Expiration__c;
        newCase.Warranty_Battery_Years__c = cd.Warranty_Battery_Years__c;
        newCase.Warranty_Storage_Expiration_Date__c = cd.Warranty_Storage_Expiration_Date__c;
        newCase.Warranty_Notes__c = cd.Warranty_Notes__c;
        newCase.Additional_Emails__c = cd.Additional_Emails__c;
        newCase.Tracking_Number__c = cd.Tracking_Number__c;
        newCase.SuppliedEmail = cd.SuppliedEmail;
        newCase.Make_this_my_case__c = cd.Make_this_my_case__c; 
        newCase.Reason = cd.Reason;
        newCase.Issue_1__c = cd.Issue_1__c;
        newCase.Issue_2__c = cd.Issue_2__c;
        newCase.Issue_3__c = cd.Issue_3__c;
        newCase.Details_1__c = cd.Details_1__c;
        newCase.Details_2__c = cd.Details_2__c;
        newCase.Details_3__c = cd.Details_3__c;
        newCase.Quantity1__c = cd.Quantity1__c;
        newCase.Quantity2__c = cd.Quantity2__c;
        newCase.Quantity_3__c = cd.Quantity_3__c;
        newCase.Add_more_issues1__c = cd.Add_more_issues1__c;
        newCase.Add_more_issues2__c  = cd.Add_more_issues2__c;
        newCase.Isclone__c=True;
        System.debug('cd.Latitude__c'+cd.Latitude__c);
        insert newCase;
        
      
        
        List<ContentDocumentLink> clonedContentDoc = new List<ContentDocumentLink>();
        for(ContentDocumentLink cdl :[SELECT ContentDocumentId,Id,IsDeleted,LinkedEntityId,ShareType,SystemModstamp,Visibility FROM ContentDocumentLink where LinkedEntityId=:this.recordId]){
            ContentDocumentLink newCdl = cdl.clone(false,true);
            newCdl.LinkedEntityId = newCase.id;
            clonedContentDoc.add(newCdl);
        }
        if(!clonedContentDoc.isEmpty()){
            System.debug('Inside ClonedContentDoc');
            System.debug('ClonedContentDoc'+clonedContentDoc.size());
            insert clonedContentDoc;
        }
        
        
        List<CaseComment> cloneComments = new List<CaseComment>();
        for(CaseComment cc : [Select Id, ParentId, IsPublished, CommentBody, CreatedById, CreatedDate, SystemModstamp, LastModifiedDate, LastModifiedById, IsDeleted From CaseComment where ParentId=:this.recordId]){
            CaseComment newcasecomment = cc.clone(false, true);
            newcasecomment.ParentId = newCase.id;
            System.debug('newcasecomment.ParentId'+newcasecomment.ParentId);
            cloneComments.add(newcasecomment);
        }
        if(!cloneComments.isEmpty()){
            System.debug('Inside CloneComments');
            System.debug('CloneComments'+cloneComments.size());
            insert cloneComments;
        }
        
        List<Task> clonedTasks = new List<Task>();
        for(Task t : [Select id, WhatId, OwnerId, Subject, Status, ActivityDate, Priority from Task where WhatId =:this.recordId]){
            Task newtask = t.clone(false, true);
            newtask.WhatId = newCase.id;
            System.debug('newtask.WhatId'+newtask.WhatId);
            clonedTasks.add(newtask);
        }
        if(!clonedTasks.isEmpty()){
            System.debug('Inside ClonedTasks');
            System.debug('ClonedTasks'+clonedTasks.size());
            insert clonedTasks; 
        }
        
        List<Event> clonedEvent = new List<Event>();
        for(Event e : [Select id, Subject, Location, Description, DurationInMinutes, ActivityDateTime, EndDateTime, RecurrenceStartDateTime, StartDateTime, Type, WhatId from Event where WhatId =: this.recordId]){
            Event newevent = e.clone(false, true);
            newevent.WhatId = newCase.id;
            System.debug('newevent.WhatId'+newevent.WhatId);
            clonedEvent.add(newevent);
        }
        if(!clonedEvent.isEmpty()){
            System.debug('Inside ClonedEvent');
            System.debug('ClonedEvent'+clonedEvent.size());
            insert clonedEvent; 
        }
        
        List<EmailMessage> clonedEmail = new List<EmailMessage>();
        for(EmailMessage email : [Select id,ContentDocumentIds, ParentId, ActivityId, BccAddress, CcAddress, FromAddress, FromName, Subject, TextBody, Status, HasAttachment,MessageDate from EmailMessage where ParentId =: this.recordId]){
            EmailMessage newemail = email.clone(false, true,true,true);
            newemail.ParentId = newCase.id;           
            newemail.FromAddress ='supportsandbox@nextracker.com';
      
            System.debug('newemail.FromAddress'+newemail.FromAddress);
            clonedEmail.add(newemail);
      }
        if(!clonedEmail.isEmpty()){
            System.debug('Inside ClonedEmail');
            System.debug('ClonedEmail'+clonedEmail.size());
            insert clonedEmail; 
        }         
        return new ApexPages.StandardController(newCase).view();
    }      


Thank in Advance,
Mahesh Babu