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 :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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.

 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Happy Coding :)

Post a Comment

7 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
    2. How does the recordID get passed into the class? Be nice to see the full application of this concept, since inserting a file into contentdocumentlink tends to cause dml errors.

      Delete
    3. How would one go about cloning a contentdocument?

      Delete
    4. Are you trying deep clone here ?

      Delete
    5. I am also facing this issue, on delete of original file the cloned one is also getting deleted. how can we clone contentdocument

      Delete