How to Clone related Files in Salesforce

How to clone related Files of an object in Salesforce ?



In salesforce while you are cloning or deep cloning an object you might need to clone related files also of that object.

Files are saved in ContentDocumentLink object in salesforce. You could google the fields of this object for reference.

You can not clone this object directly it will throw an error like "LinkedEntityId is not writable"

To solve this issue we have to clone files one by one and than insert new LinkedEntityId in it to link this with your object.

Here is code below :

List con = [SELECT ContentDocumentId,ContentDocument.Title, 
ContentDocument.ContentModifiedDate, ContentDocument.ContentSize FROM 
ContentDocumentLink WHERE LinkedEntityId=:recordId];

List conClone = new List();
                        for(ContentDocumentLink file: con){
                            ContentDocumentLink newclnk = file.clone();
                            newclnk.LinkedEntityId = YOUROBJECTID;
                            newclnk.ShareType = 'V';
                            conClone.add(newclnk);
                            
                        }
                        
                        insert conClone;




Share this blog with your friends if you find this post useful.

Post a Comment

4 Comments

  1. This is good but contentdocumentlink is just a reference. If i delete the file from original record then the new cloned object will also lead to deletion of file since both are same file with multiple references right? Either we should clone contentdocument too!!

    ReplyDelete
    Replies
    1. Yes in that case we can clone contentdocument too.

      Delete