+ Start a Discussion

Issue with file count on Custom object

I have an apex class which updates the files count on custom object called Declined_Policy__c.

Below is my apex class:
public with sharing class Policy_FileCountClass {

    public static void updateAttachmentCountOnDps(List<ContentDocumentLink> DocuLinks) {
        Set<Id> policyids = new Set<Id>();
        for (ContentDocumentLink cdl : DocuLinks) {

        List<Declined_Policy__c> dpsToUpdate = [
            SELECT Id, Attachments__c,
                (SELECT Id FROM ContentDocumentLinks) 
            FROM Declined_Policy__c WHERE Id IN :policyids
        for (Declined_Policy__c dp : dpsToUpdate) {
            dp.Attachments__c = dp.ContentDocumentLinks.size();
        update dpsToUpdate;


Now, as per the above logic, i can able to the count in attachments__c field if there is any file attached to the record or if it is deleted. I could able to see the count in these scenarios. But the issue is that, if there is no file attached to the record when the record is inserted, the attachments__c field will be blank instead of displaying 0

Is there any way that i can update the above logic to get the attachments__c to display 0 by default if there is no file attached to it. Please suggest.
Can you give this a try ?
dp.Attachments__c = dp.ContentDocumentLinks.size();
dp.Attachments__c = dp.ContentDocumentLinks.size() > 0?dp.ContentDocumentLinks.size():0;
@SFDC_Saurabh, I could still see the null/blank value instead of 0. Could you please suggest any update here?