In this article we will learn how to create Attachment in Salesforce using apex and link it to a record. If you love to learn by watching video content then scroll down to the youtube video.
Introduction
In order to create attachment in Salesforce using Apex we have to use the Attachment object. Attachments are a powerful feature in Salesforce that allow users to upload and associate files with records. While Salesforce now encourages the use of ContentDocument and ContentVersion (via Files), there are scenarios where working with Attachments is necessary, particularly in legacy systems. In this article, we will cover how to create attachments programmatically using Apex in Salesforce.
If you want to learn about generating and storing PDF using ContentVersion and ContentDocument then checkout this article.
Attachment Object
The Attachment Object is used to store file attachments and relate them with Salesforce record. Have a look at key fields:
- ParentId: The Id of the record to which the attachment should be associated.
- Name: The name of the file we are creating.
- Body: The content of the file in the Blob format.
- ContentType: The MIME type of the file for example application/pdf.
Example Code
Here is the code example where we are creating an attachment and relating it with Account record. You can relate it with any record by changing the parentId.
String pdfContent = 'This is a test String'; Attachment attachment = new Attachment(); attachment.contentType = 'application/pdf'; attachment.name = 'Sample'+'.pdf'; attachment.parentId = '5005i00000SonMvAAJ'; attachment.body = Blob.toPdf(pdfContent); insert attachment;
Above is the code which will create a PDF as an attachment and link it to parent account record. It will have content “This is a test String.”
Watch below video to learn more.
We hope now you know how to create an attachment using Apex in Salesforce and link it to a record. Let us know on which topic we should write next.