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
sfdc girlygeeksfdc girlygeek 

I want to show error on more than 4 attachments using trigger

I tried but my code is not working
trigger AttachmentTrigger on Attachment (before insert) {
    Set<Id> attid = new Set<Id>();  
    for(Attachment att : Trigger.new){
        attid.add(att.parentId);
        
    }
    Map<Id,Account> acMap = new Map<Id,Account>([select id,(select id,parentId from attachments) from Account where Id IN : attid]);

    for(Attachment att : Trigger.New){
       
        if(acMap.get(att.parentId).attachments.size() > 4 ){
            
            att.adderror('You can not add more than 4 attachments!');
        }
    }
}

Can someone help me on this
Best Answer chosen by sfdc girlygeek
sfdcMonkey.comsfdcMonkey.com
Hi update line number 11 : it will be 3 not 4

  if(acMap.get(att.parentId).attachments.size() > 3 ){

Thanks let us know if it helps you

All Answers

sfdcMonkey.comsfdcMonkey.com
Hi update line number 11 : it will be 3 not 4

  if(acMap.get(att.parentId).attachments.size() > 3 ){

Thanks let us know if it helps you
This was selected as the best answer
sfdc girlygeeksfdc girlygeek
Hi Piyush, It's not working..
ManojjenaManojjena
Hi ,

Please check below code ,
 
trigger AttachmentTrigger on Attachment (after insert) {
    Set<Id> parentIdSet = new Set<Id>();
    Map<Id,Account> accMap;
    if(Trigger.isInsert){
        
        for(Attachment att : Trigger.new){
            if(String.valueOf(att.ParentId).startsWith('001')){
               parentIdSet.add(att.ParentId); 
            }  
        } 
    }
    if(!parentIdSet.isEmpty()){
           accMap =new Map<Id,Account>([SELECT id,(SELECT Id FROM Attachments) FROM Account WHERE  Id IN : parentIdSet LIMIT 50000]);
           if(!accMap.isEmpty()){
                for(Attachment att : Trigger.new){
                    if(accMap.get(att.parentId).attachments.size() > 4 ){
                       att.addError('You can not add more than 4 attachments!');
                    }
                }
            } 
        }
    }

Let  me know  if it helps !!!
Thanks 
Manoj
sfdc girlygeeksfdc girlygeek
Thanks Piyush and Manoj. It's working.
sfdcMonkey.comsfdcMonkey.com
good to hear :) close your question with best answer so it will be removed from unsolved queue