+ Start a Discussion
Shawn Reichner 29Shawn Reichner 29 

Cloning Custom Object Record and Associating Existing Files to New Cloned Record

Hello Awesome Devs!

Recently moved to Lightning and was used to dealign with attachments, but now trying to clone a record to have its files also associated to the new cloned version of the record as well as staying associated with the initial starting record. 

I am calling the class via a process that is called when a checkbox is marked true. 

Right now the error I get is very vauge and I am not sure what I need to refactor.  Error =  An Apex error occurred: System.UnexpectedException: null

Can someone take a look at my code below and let me know how I can can applomplish this feat?...

Thank you in advance for your help!
 
public class cloneTicketWithRelated {

    @InvocableMethod
    public static void cloneRecords(List<Ticket__c> ticketIds){
      
        List<Ticket__c> ticketsToProcess = ticketIds;
 	    List<Ticket__c> cloneList = ticketsToProcess.deepClone();
        
        List<Ticket__c> clonedTickets = new List<Ticket__c>();
       
        for(Ticket__c t : cloneList){
            clonedTickets.add(t);
        }
        
        if(clonedTickets.size()>0){
            insert clonedTickets;
        }
   }    
}

 
ayu sharma devayu sharma dev
Hello Shawn

It looks like the TicketIds you are passing in the method may be null.
 
List<Ticket__c> ticketsToProcess = ticketIds;
List<Ticket__c> cloneList = ticketsToProcess.deepClone();
using a deep clone method on Null might giving you an Error.
Try to debug your values and let me know the results.

Thanks 
Ayush
sfdcBahusfdcBahu
Data structure of the Files are totally different from Attachment. For Files, SF uses ContentDocument and ContentVersion objects in the backend. You dont have to clone the File which will unnecessarily take more storage. SF uses ContentdocumentLink object to establish link between the File(ContentDocument) and the Sobject records.  So all you have to do is Create another ContentDocumentLink record to establish relationship to your Cloned Ticket Record. So same File linked to 2 tickets.