How to restrict multiple attachments on a Salesforce Custom object

Author - Neha Mishra
12.11.2018
|
0 Comments
||

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 relatedAttachments = [SELECT COUNT(Id), ParentId FROM Attachment WHERE Parentid IN: customObjectIdList GROUP BY ParentId ];

       	 
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');    	
}
}

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *