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';
                        insert conClone;

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

Post a Comment


  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!!

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

    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.

    3. How would one go about cloning a contentdocument?

    4. Are you trying deep clone here ?