How to Create Content Note Using Apex in Salesforce?

In this article we will learn how to insert a content note in Salesforce using Apex. We will also learn how to relate the Note with a Salesforce record.

In order to create Content Note we will make use of ContentNote object and we will use ContentDocumentLink to relate the note with a Salesforce record.

//Create a ContentNote 
ContentNote newNote = new ContentNote();
newNote.Title = 'Notes-101';
String body = 'This is a sample note created.';
newNote.Content = Blob.valueOf(body.escapeHTML4());
insert newNote;
Id noteId = newNote.Id;

String recordId = '0035i0000FvxXqrAQE';

// Create a ContentDocumentLink to relate the note to a record
ContentDocumentLink link = new ContentDocumentLink();
link.LinkedEntityId = recordId;
link.ContentDocumentId = noteId;
link.ShareType = 'V'; // Viewer access
link.Visibility = 'AllUsers'; // Visible to all users 
insert link;
System.debug('Content Note Created with Id: '+noteId);

Execute the code from Anonymous window. You will get below error.

You are getting this error because Notes are not enabled in Salesforce. In order to enable notes follow below steps:

  1. Go to Setup.
  2. Search for Note Settings and click on it.
  3. Check the checkbox which says Enable Notes and click on save button. Check the below image for reference.

Now the notes are enabled. Execute the code again from the anonymous window and there will be no error this time.

Also, check out the below video on How to Create Content Note Using Apex in Salesforce.

I hope now you will be able to create note using Apex in Salesforce.

Leave a Comment