function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Lena RLena R 

Count attachments on custom record in Lightning

I need to be able to count attachments on a custom object in Lightning: every time an attachment is added - increase the counter, and when deleted - decrease.

I was able to implement the attachment counter in Classic using a trigger on Attachment object, but it doesn't work in Lightning because a differnt object is used for storring attachments - ContentDocument. The problem is that querying ParentId field through SOQL on ContentDocument returns nothing.

Am I looking at the wrong object? Is there another way to find out ParentId on attachments added through Lightning?

Thank you in advance
Best Answer chosen by Lena R
Akhil AnilAkhil Anil
In your case, you just need the first query as you only want the count of attachments. So just the first query should suffice your requirement.

All Answers

Akhil AnilAkhil Anil
Hi Lena,

You were pretty close. So you are indeed at the right place to find the attachment records. In Lightning, attachments are stored with references in two object i.e. ContentDocument and ContentDocumentLink. The ParentId is actually stored in the ContentDocumentLink record in a field called as LinkedEntityId.

So the first step here is to fire a query on the ContentDocumentLink object with a filter on the LinkedEntityId like this
 
SELECT Id, ContentDocumentId, LinkedEntityId FROM ContentDocumentLink where LinkedEntityId = 'Your Parent ID here'

The above query will get you the ContentDocumentID which you can use to filter the query on ContentDocument like this
 
Select Id ,Title from ContentDocument Where ID = 'ContentDocumentId from the previous query'

This would return the actual attachment record.

Hope that helps

Kindly mark it as an answer if that resolves your query.
Akhil AnilAkhil Anil
In your case, you just need the first query as you only want the count of attachments. So just the first query should suffice your requirement.
This was selected as the best answer
Lena RLena R
My further research and development showed that the solution suggested by Akhil Anil is actually correct.

After discovering that when a new file is attached to an object (in my case a custom object) in Lightning, two ContentDocumentLink records are created: one with an ID of the user uploaded the document stored as LinkedEntityId; and the other - with an ID of the related object, I was able to implement a counter for documents attached to a custom object through Lightning Experince.

Thank you Akhil!