[SalesForce] How to insert a new record on the AttachedContentNote object

I am trying to create a custom component to list and insert notes in a Account record. After some research, I founded that to get all the notes related to my account record, I needed to do the following SOQL :

[SELECT (SELECT Id, Title, TextPreview,Createdby.Name, CreatedDate FROM AttachedContentNotes order by createddate asc) FROM Account where Id=: recordId];

That sub-query creates a column with all the notes related to my account record in a JSON-like format. But before I get there, I founded some other objects that are related to the AttachedContentNotes object, like : Note, ContentNote and Attachment.
I tried to query all of those using my account ID as a parameter but they all look empty, even that the notes are there when I look on the related list.

So I tried to use the 'inspector mode' on Chrome and discovered a different ID:

enter image description here
So I tried to run this method :

String sObjName = myId.getSObjectType().getDescribe().getName();

and founded that it was related to a ContentDocument object, that doesn't has any records as well…but that was fine by me, I created a function and got the data that I was looking for anyway (even that it was not the way that I really wanted).

Now I faced a new challenge, how can I insert a new note using APEX, since the AttachedContentNote does not support query/dml and records inserted manually on the other objects that I listed above doesn't work as well? Which objects I specifically need to handle in order to achieve this?

Thanks in advance.

Best Answer

Datamodel

First take glance on the datamodel:

Conceptual approach

In my experience two steps are needed to attach new Notes to a record. This works very similar to files btw.

  • first you have to create and insert a ContentNote and obtain the Id of the newly created Note. You can image the new ContentNote as a Note not linked to any record yet.
  • now to connect your record to the Note you need to create a new ContentDocumentLink and set there your record.Id and the Id of the new ContentDocument.

All this is necessary because you can reuse Files and Notes on many records. Therefore the junction object ContentDocumentLink is used to provide an m:n datamodel.

Related Topic