Friday 20 August 2021

How to Create/Delete file attachments(Content Document) through Apex ?

 There are 3 standard salesforce objects to store file attachments.

Content Document, ContentDocumentVersion, ContentDocumentLink. 

Here is the article to talk about these objects and relationship. 

https://www.forcetalks.com/blog/contentdocument-and-contentversion-in-salesforce-an-overview/

ContentDocumentVersion

ContentDocumentLink






This post is all about how to create/delete content document though Apex. Here is code snippet

// Insert Content Version record
ContentVersion contentVersionRec = new ContentVersion(Title='filename',PathOnClient ='FileName.pdf',VersionData = bodyBlob,origin = 'H');
INSERT contentVersionRec; // this will insert one record in ContentDocument and ContentVersion ,ContentDocument  is parent and ContentVersion is child record

// get contentdocument id
contentVersionRec = [SELECT Id, Title, ContentDocumentId FROM ContentVersion WHERE Id = :contentVersionRec .Id LIMIT 1];

// Create Content Document Link record- This will attach file to particular record

 ContentDocumentLink contentlink = new ContentDocumentLink();
 contentlink.LinkedEntityId = 'Sobject Id'; // for example lead or opportunity record Id
 contentlink.contentdocumentid = contentVersionRec .contentdocumentid;
 contentlink.ShareType = 'I';
 contentlink.Visibility = 'AllUsers';
 INSERT contentlink;

Note - Same content document can be shared with other objects, we just have to create ContentDocumentLink records.

Deleting File Attachments

//Delete ContentDocumentLink
Delete [select id from ContentDocumentLink where contentdocument.Title = 'ES-0275' and LinkedEntityId = '00Q1Q00001IZxcAUAT'];

// Delete Content Version 
Delete[select id from ContentVersion where Title = 'ES-0275'];

// Delete Content Document
Detete[select id from ContentDocument where Title = 'ES-0275'];
Note - If we delete content document then contentdocumentversion and contentdocumentlink will be deleted automatically.




No comments: