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
Roman RegmiRoman Regmi 

Trigger to check if file is attached to a custom object record.

I have a scenario where I need to check if a file has been added to a custom object record. If a file is already present, then the user should not be able to upload more files. Else, the user should be able to upload files.
AnkaiahAnkaiah (Salesforce Developers) 
Hi Roman,

Try with below code and replace your custom object name.
trigger documentcheck on ContentDocumentLink (before insert) {
    
     Set<Id> parentQuoteDocumentIds = new Set<Id>();

        for(ContentDocumentLink cdl : Trigger.new){

            parentQuoteDocumentIds.add(cdl.LinkedEntityId);
            
                    }

       List<ContentDocumentLink> CDLList = new List<ContentDocumentLink>([SELECT id, LinkedEntityId fROM ContentDocumentLink WHERE LinkedEntityId IN : parentQuoteDocumentIds]);
    
    	for(ContentDocumentLink a : Trigger.new) {             
                if(CDLList.size()>0 && (a.LinkedEntityId).getSObjectType().getDescribe().getName() == 'Customobject__c' ) {
                   a.addError('You cannot add More than one file');    
                }	    
        
    }
       
}

If this helps, Please mark it as best answer.

Thanks!!
Roman RegmiRoman Regmi
Did not work.