+ Start a Discussion
Bhargav SurapaneniBhargav Surapaneni 

capturing number of attachments

Hi all,

I have some custom object and I want to capture the number of attachments attached to that particular record. Please help me how to achieve this.

Thanks in Advance
Best Answer chosen by Bhargav Surapaneni
AvaneeshAvaneesh
Hi bhagarv 

Can you try ​second code which i provided you that was working fine and  i will check after some time the first code 

I am 100% sure it will work fine 
trigger CountTotalNoOfAttachmentOfAccount on Attachment (after insert,after delete,after undelete) {
    List<Attachment> data;
    if(trigger.isinsert)
    {
        data=trigger.new;
    }else
    {
        data=trigger.old;
    }
List<id> Accountid = new List<id>();
    List<id> attid= new List<id>();
    //List<Account> allacc= new List<Account>([select id from Account]);
    for(Attachment att:data)
    {
        Accountid.add(att.ParentId);
        System.debug('***********'+att.ParentId +'************');
        attid.add(att.Id);
    }
    List<Account> oldAccountWithAtt = new List<Account>([select id,total_no_of_attachment__c from account where id in:accountid]);
    //select count(id) from Attachment where parentid ='0016F00001sVQsX'  group by parentid
    List<AggregateResult> totalCount= [select count(id) total from Attachment where parentid in:oldAccountWithAtt group by parentid ];
    Integer i=0;
    List<Account> ls = new List<Account>();

    for(Attachment atr:data)
    {
       account ac=oldAccountWithAtt.get(i);
        ac.Total_No_of_Attachment__c=Integer.valueOf(totalCount[i].get('total'));
        i++;
       ls.add(ac);
    }
    update ls;
    
}


 

All Answers

Karan Shekhar KaulKaran Shekhar Kaul
You can write a trigger on attachement to update parent custom object.
https://help.salesforce.com/articleView?id=000181538&type=1
AvaneeshAvaneesh
Hi Bhargav 

1--To Count no of attachment you need a field in your custom object type number 
2-- after that write a trigger for attachment with respect to your custom object 

here is my code i was writing this trigger to count Accounts attachment with a custom field Total no of attachment in Account
 
trigger CountTotalNoOfAttachmentOfAccount on Attachment (after insert,after delete,after undelete) {
    List<Attachment> data=trigger.isInsert? trigger.old:trigger.new;
   
    set<id> uniqueid= new set<id>();
    for(Attachment at:data)
    {
        if(string.valueOf(at.parentid).startswith('001'))
        uniqueid.add(at.parentid);
    }
            List<AggregateResult> allatt = [select parentid pi,count(id) total from Attachment where parentid in:uniqueid group by parentid];
            map<String,Integer> newData= new map<String,Integer>();
    for(AggregateResult ar:allatt)
    {
        newData.put(string.valueOf(ar.get('pi')),Integer.valueOf(ar.get('total')));
    }
    List<Account> ls= new List<Account>();
    for(String ide:uniqueid)
    {
        if(newData.containsKey(ide))
        {
            account ac= new account(id=ide,total_no_of_attachment__c=newData.get(ide));
            ls.add(ac);
        }
    }
    if(ls.size()>0)
    update ls;


please mark as best answer if was helpful for you if any else requirment let me know

Thank you 
Avaneesh Singh
Bhargav SurapaneniBhargav Surapaneni
Hi Avaneesh,
I tried with the code which you have provided but it is not updating no.of attachments and throwing some error
AvaneeshAvaneesh
Hi bhargav ,
Show me error which it was throwing .
 
AvaneeshAvaneesh
Hiii bhargav 
i dont understand why u get error bt this code i used in my org working fine 
please create a field total no of attachment in account object and this will 100% work fine 



trigger CountTotalNoOfAttachmentOfAccount on Attachment (after insert,after delete,after undelete) {
    List<Attachment> data;
    if(trigger.isinsert)
    {
        data=trigger.new;
    }else
    {
        data=trigger.old;
    }
List<id> Accountid = new List<id>();
    List<id> attid= new List<id>();
    //List<Account> allacc= new List<Account>([select id from Account]);
    for(Attachment att:data)
    {
        Accountid.add(att.ParentId);
        System.debug('***********'+att.ParentId +'************');
        attid.add(att.Id);
    }
    List<Account> oldAccountWithAtt = new List<Account>([select id,total_no_of_attachment__c from account where id in:accountid]);
    
    List<AggregateResult> totalCount= [select count(id) total from Attachment where parentid in:oldAccountWithAtt group by parentid ];
    Integer i=0;
    List<Account> ls = new List<Account>();

    for(Attachment atr:data)
    {
       account ac=oldAccountWithAtt.get(i);
        ac.Total_No_of_Attachment__c=Integer.valueOf(totalCount[i].get('total'));
        i++;
       ls.add(ac);
    }
    update ls;
    
}


Thank you 
Avaneesh Singh
Bhargav SurapaneniBhargav Surapaneni

HI Avaneesh Singh

I have changed object from account to promotion


trigger NoofAttachmentpromotion on Attachment (after insert,after delete,after undelete) {
    List<Attachment> data=trigger.isInsert? trigger.old:trigger.new;
   
    set<id> uniqueid= new set<id>();
    for(Attachment at:data)
    {
        if(string.valueOf(at.parentid).startswith('a0a'))
        uniqueid.add(at.parentid);
    }
            List<AggregateResult> allatt = [select parentid pi,count(id) total from Attachment where parentid in:uniqueid group by parentid];
            map<String,Integer> newData= new map<String,Integer>();
    for(AggregateResult ar:allatt)
    {
        newData.put(string.valueOf(ar.get('pi')),Integer.valueOf(ar.get('total')));
    }
    List<Promotion__c> ls= new List<Promotion__c>();
    for(String ide:uniqueid)
    {
        if(newData.containsKey(ide))
        {
            Promotion__c pr= new Promotion__c(id=ide,total_no_of_attachment__c=newData.get(ide));
            ls.add(pr);
        }
    }
    if(ls.size()>0)
    update ls;
}

When the first attachment is attached it didn't throw any error and even that field is not updated.
When I tried to add 2nd one it is throwing error at the UI level

Error: Apex trigger NoofAttachmentpromotion caused an unexpected exception, contact your administrator: NoofAttachmentpromotion: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.NoofAttachmentpromotion: line 5, column 1

Thank you 

AvaneeshAvaneesh
Hi bhagarv 

Can you try ​second code which i provided you that was working fine and  i will check after some time the first code 

I am 100% sure it will work fine 
trigger CountTotalNoOfAttachmentOfAccount on Attachment (after insert,after delete,after undelete) {
    List<Attachment> data;
    if(trigger.isinsert)
    {
        data=trigger.new;
    }else
    {
        data=trigger.old;
    }
List<id> Accountid = new List<id>();
    List<id> attid= new List<id>();
    //List<Account> allacc= new List<Account>([select id from Account]);
    for(Attachment att:data)
    {
        Accountid.add(att.ParentId);
        System.debug('***********'+att.ParentId +'************');
        attid.add(att.Id);
    }
    List<Account> oldAccountWithAtt = new List<Account>([select id,total_no_of_attachment__c from account where id in:accountid]);
    //select count(id) from Attachment where parentid ='0016F00001sVQsX'  group by parentid
    List<AggregateResult> totalCount= [select count(id) total from Attachment where parentid in:oldAccountWithAtt group by parentid ];
    Integer i=0;
    List<Account> ls = new List<Account>();

    for(Attachment atr:data)
    {
       account ac=oldAccountWithAtt.get(i);
        ac.Total_No_of_Attachment__c=Integer.valueOf(totalCount[i].get('total'));
        i++;
       ls.add(ac);
    }
    update ls;
    
}


 
This was selected as the best answer
Bhargav SurapaneniBhargav Surapaneni
Thank you so much for your time.
It was working fine but i added one try catch block because when we are deleting all attachments
It is showing exception while deleting last attachment

NoOfAttachmentpromotion: execution of AfterDelete
caused by: System.ListException: List index out of bounds: 0
Trigger.NoOfAttachmentpromotion: line 28, column 1

 try{
        ac.Total_No_of_Attachment__c=Integer.valueOf(totalCount[i].get('total'));
        }
        catch(Exception ex){
            ac.Total_No_of_Attachment__c=0;
        }