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
aklkkaklkk 

how to write a trigger for prevent the more then one attachement on parent record?

HI All,


Please solve the problem 
how to prevent the more then one attachement on parent record ?



Thanks 
aklkk
Shaik Naga janiShaik Naga jani
Hi aklkk,
check this sample trigger(not tested), I wrote based on opportunity, you can extend this functionality to few more objects.
if opportunity record already has an attachment it will throw an error otherwise it will insert attachment on record.
trigger AttachmentCheck on Attachment (before insert, before update) {
    set<Id> setOppIds = new set<Id>();

    for(Attachment atchIterator : trigger.new) { 
        if(String.valueOf(atchIterator.ParentId).substring(0, 3) == Opportunity.sObjectType.getDescribe().getKeyPrefix()) {
            setOppIds.add(atchIterator.ParentId);
        }
    }
    
    map<Id, Attachment> mapParntIdWithAtt = new map<Id, Attachment>();
    if(!setOppIds.isEmpty()) {
        list<Attachment> lstAttachs = [Select Id, Name, ParentId from Attachment where ParentId IN :setOppIds];
        for(Attachment atIterator : lstAttachs) {
            mapParntIdWithAtt.put(atIterator.ParentId, atIterator);
        }
    }
    
    for(Attachment atIterator : trigger.new) {
        Attachment objAttach = mapParntIdWithAtt.get(atIterator.ParentId);
        System.debug('Attachmet ====> '+objAttach);
        if(objAttach != null) {
            atIterator.addError('Attachment already attached in record.');
        }
    }
}

Kindly mark this as solved if the reply was helpful.
Thanks
Shaik