You need to sign in to do that
Don't have an account?
Phuc Nguyen 18
Get number of Files attached to a record
Need help counting the number of files atatched to a custom object.
Should I be looking at ContentDocumentLinks
Should I be looking at ContentDocumentLinks
if ( Trigger.isInsert || Trigger.isDelete ){ Set<Id> FileCount = new Set<Id>(); for(SObject cdl : Trigger.new){ ContentDocumentLink cdls = ( ContentDocumentLink ) cdl; FileCount.add(cdls.LinkedEntityId); } List<File_c> fileList = [SELECT Id, (SELECT Id FROM ContentDocumentLinks) FROM File_c WHERE Id IN :FileCount]; for(File_c fl : fileList){ fl.Number_of_Files__c = fileList.size(); } }
1. get the list or IDs, put in a list, lets call it listIds;
2. use the following query:
select count(id),FirstPublishLocationId from contentversion where IsLatest = true and FirstPublishLocationId in :listIds group by FirstPublishLocationId
3.Loop through the trigger.new and query result of step 2, set number_of_files__c.
Check below examples to number of Files attached to a record
https://salesforce.stackexchange.com/questions/312483/count-of-files-attached-to-custom-object-record
https://developer.salesforce.com/forums/?id=906F0000000g0oZIAQ
Thanks,
Please use below query :-
If this solution is usefull for you, Please mark as a Best Answer to help others.
Regards
Mukesh
@David Zhu ,
1. get the list or IDs, put in a list, lets call it listIds; --- is this the custom object id?---
2. use the following query:
select count(id),FirstPublishLocationId from contentversion where IsLatest = true and FirstPublishLocationId in :listIds group by FirstPublishLocationId -- is contentversion where thh files are stored?
List<Id> ids = new List<Id>();
if (trigger.isInsert)
{
for (SObject cdl : Trigger.new){
ids.add(cdl.id);
}
}
else if (trigger.isDelete)
{
for (SObject cdl : Trigger.old){
ids.add(cdl.id);
}
}
2 is contentversion where thh files are stored? -Yes
I if I am querying the contentversion object how am going to assign the count/size to the custom object?
AggregateResult[] groupedResults = [select count(id),FirstPublishLocationId from contentversion where IsLatest = true and FirstPublishLocationId in :ids group by FirstPublishLocationId ];
for (AggregateResult ar : groupedResults) {
// you get the record id and count and assign accorindingly
System.debug('Customer Object ID ' + ar.get('FirstPublishLocationId '));
System.debug('File count' + ar.get('expr0'));
}