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
Manuel Briceño 3Manuel Briceño 3 

Limiting to number of attachments in a record to 1

Good morning folks,

I was wondering if its is possible to have a trigger on attachment whereas it would check if the record already has an attached file, and if so it would give an error and would not allow anymore files to be attached on said record.

And if the latter is indeed possible what should the trigger be counting? Attachments or Contentdocument?

Thanks in advanced for the help.
SEKAR RAJ.SEKAR RAJ.
Hi Manuel,
You will have to write an Apex Trigger(After Insert) on the Attachment object, that would see if the Attachment getting created is the desired one and also is it getting attached to the Opportunity record. If so, you can then update may be a Checkbox field on the Opportunity record. Then you can make use of this very Checkbox in the Entry Criteria. Note that you may also have to build another Apex Trigger(Before Delete) in which you will un-check the Checboxif in case a User deleted the Attachment. Also, another Apex Trigger(After Undelete) to check the Checkbox again if the User undeletes it from Recycle Bin. So you may need some considerable Development Effort to get this done.


Thanks,
SEKAR RAJ
Manuel Briceño 3Manuel Briceño 3
Yeah that sounds like a lot more work of what I am capable of doing, so is there any other way to achieve the same result? or is this the only/best way to do it?
Abhishek BansalAbhishek Bansal
Hi Manuel,

You can write a before insert trigger on Attachment and check whether the ParentId of the newly inserted record contains an Attachment or not. Based on the results you can throw error on the Attachment. Please find the trigger code below:
trigger checkAttachment on Attachment (before insert) {
    Set<Id> parentIds = new Set<Id>();
    for(Attachment attach : trigger.new) {
        parentIds.add(attach.ParentId);
    }
    Set<Id> existingAttachments = new Set<Id>();
    for(Attachment existingAttachment : [Select id, ParentId from Attachment where ParentId IN :parentIds]) {
        existingAttachments.add(existingAttachment.ParentId);
    }
    
    for(Attachment attach : trigger.new) {
        if(existingAttachments.contains(attach.ParentId)) {
            attach.addError('Record already contains an Attachment');
        }
    }
}

The error will be shown when you click on the Attach button as shown below:
 User-added image
Thanks,
Abhishek Bansal.