Wednesday 2 March 2022

How to delete files from object by Apex

Delete files, Change related record of files / Attachments / ContentDocument/ ContentDocumenLink from object by Apex.

Here we will consider the examples of files on Account object. Actually we can not directly change the related record id on files. To change related id we have to follow below steps: 

1. First , files are stored in contentDocument object and linked with ContentDocumentLink object.

2. So if you want to update related record id then you must have to updatte ContentDocumentLink object.

3. But Related Object Id is stored in LinkedentityId field of ContentDocumentLink object and this field can not be overwritten. so we can not directly change related record Id.

4. Then to change related record id , we first need to delete record of ContentDocumentLink object then insert new record with same data with your new related record Id. 

Lets see steps below:

To fetch files , use below query

List<ContentDocumentLink> listContentLink = [Select Id,Linkedentity.name,LinkedentityId,ContentDocumentId from ContentDocumentLink Where LinkedentityId='0017F00001eFkvN'];  //LinkedentityId - is Account Id

List<ContentDocumentLink> listCloneData = new List<ContentDocumentLink>();

List<ContentDocumentLink> listDeleteData = new List<ContentDocumentLink>();

for(ContentDocumentLink objConDoc : listContentLink){

    ContentDocumentLink objCloneContentDoc = objConDoc.clone(); // Take clone of existing data

    objCloneContentDoc.LinkedentityId = '0017F00000yz5xpQAA'; // Assign new account record Id

    listCloneData.add(objCloneContentDoc); // add new data in clone list

    listDeleteData.add(objConDoc);

}

// First insert data 

if(!listCloneData.isEmpty()){

    insert listCloneData;

}

// Delete data

if(!listDeleteData.isEmpty()){

    delete listDeleteData;

}


File data of account object and needs to delete by apex.

Image 1: Account with File before delete


Account with File after delete

Image 2: Account with File after delete


0 comments:

Post a Comment

If you have any doubts, please let me know.