Restrict a user to create multiple attachments on a specific custom object.
To accomplish this, as it is not possible to create a process builder or workflow on Notes & Attachments object, neither we have a privilege to view attachment object inside Salesforce, so creating a trigger will work in this case.
Here are the steps to create the trigger in Salesforce:-
1. Go to developer console.
2. Go to New-> Apex Trigger.
3. Select the sObject name (Attachment) from drop down.
4. Specify the trigger name and save.
Functionality:-
In the Attachment trigger, retrieve all the attachments and filter them via ParentId using the Prefix of custom object. Store the parent ids in customObjectIdList from these attachments. Also, maintain a map that will hold the custom object Id and the related attachment object in customObjectByAttachObject.
for(Attachment eachAttachment : newAttachmentRecords){
//check if parent of the attachment is the custom object using prefix of the object. Say here it is ‘‘00W’’
If (String.valueOf(eachAttachment.ParentId).startsWith(‘00W’)){
customObjectIdList.add(eachAttachment.ParentId);
customObjectByAttachObject.put(eachAttachment.ParentId, eachAttachment);
}
}
After this, you may add the below code:
List
for(AggregateResult relatedAttachment : relatedAttachments ){
Id attachmentId = String.ValueOf(relatedAttachment.get('ParentId'));
// The condition below will help to identify whether it has an attachment already or not.
if(Integer.valueof(relatedAttachment.get('expr0')) >= 1){
customObjectByAttachObject.get(String.valueOf(relatedAttachment.get('ParentId'))).adderror('You can attach only one file for one custom object record');
}
}
