Monday, April 20, 2015

Trigger to Count number of Attachments on an Object in Salesforce

This article is for those who are fairly new to Apex Triggers and need help in writing the Trigger to Count number of attachments on an Object.

Below are some steps that are require to have this functionality :

Step 1: Create an Object on which you want this functionality. So for this i'm creating a Custom Object - TestObject__c. You can also use existing Standard Objects.


Step 2 : Create two Custom Fields on the Custom Object - TestObject__c, which we used on the Page Layout (for showing the attachment count) and on Trigger for counting the number of attachments.

CountAttachment__c Number(18, 0)

Total_Attachment_Count__c Formula (Number) (Contains the Value of CountAttachment__c)

Note : We used Total_Attachment_Count__c field  to display the total attachment count value on the page layout in read only mode and CountAttachment__c is actually used in the Trigger code.

Step 3 : Now we need to create an Apex Trigger on Attachments to count the number of attachments on the object. Trigger is considering all the possible scenarios in this - after insert, after update, after delete, after undelete.

Apex Trigger Code
===============


//Trigger to Count the Number of Attachments on an Object

trigger countattachment on Attachment (after insert, after update, after delete, after undelete) {
  Map<Id,List<Attachment>> parent = new Map<Id,List<Attachment>>();
  set<id> attids = new set<id>();
     
   if(Trigger.new<>null){
       for(Attachment c:Trigger.new){
           TestObject__c l;
           if(c.ParentId != null)
               attids.add(c.parentid);
       }
           
   }else if(Trigger.old != null){
       for(Attachment c:Trigger.old){
           if(c.ParentId<>null)      
               attids.add(Trigger.oldMap.get(c.id).parentid);
       }
   }
   if(attids.size()>0){
       try{
           List<Attachment> a = new List<Attachment>();
           Map<id,TestObject__c> testmap = new Map<id,TestObject__c>([select id,CountAttachment__c from TestObject__c where id IN: attids]);
           a = [select id,parentid from Attachment where parentid IN:attids];
           
           for(Attachment at: a){
               List<Attachment> llist = new List<Attachment>();
               if(parent.get(at.parentid) == null){
                   llist = new List<Attachment>();
                   llist.add(at);
                   parent.put(at.parentid,llist);
               }else if(parent.get(at.parentid) != null){
                   llist = new List<Attachment>();
                   llist = parent.get(at.parentid);
                   llist.add(at);
                   parent.put(at.parentid,llist);
               }
           }
           
           for(Id i: attids){
               if(testmap.get(i) != null && parent.get(i) != null){
                  testmap.get(i).CountAttachment__c = parent.get(i).size(); 
               
               }else if(testmap.get(i) != null && parent.get(i) == null){
                  testmap.get(i).CountAttachment__c = 0; 
               }
           }
       
           update testmap.values();
           System.Debug(testmap.values());
       }catch(Exception e){}
    }

}

Snapshot
========

28 comments:

  1. Good Post.Very helpful.

    ReplyDelete
    Replies
    1. Big data is a term that describes the large volume of data – both structured and unstructured – that inundates a business on a day-to-day basis. big data projects for students But it’s not the amount of data that’s important.Project Center in Chennai

      Python Training in Chennai Python Training in Chennai The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai

      Delete
  2. Nice Post. Best way to write bulkified trigger.

    ReplyDelete
  3. I was searching for a simple tutorial and I reached here on this blog.Nicely explained.I bookmark this.

    ReplyDelete
  4. Nice Post and very helpful post for me. I also solved my problem with this post. Thanks Sunil

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Can this be used on standard object as well? I want to calculate the number of attachments on my Tasks.

    ReplyDelete
  7. I can't get this trigger to work. :(
    Error: Compile Error: Incorrect SObject type: Attachment should be Project__c at line 3 column 1

    ReplyDelete
  8. Thank you for sharing this code .Could you please provide test class for this? Thank you inadvance

    ReplyDelete
  9. Hi, This is working for new attachments but not with existing attachments. Could you please help me with this?
    Thank you in advance.

    ReplyDelete
    Replies
    1. I am wondering the same thing. I got this working for my custom object, but it is only counting new attachments...the field is blank, even on records with existing attachments. Sunil Sharma, how can this be modified to count existing attachments with the new attachments? Thanks.

      Delete
    2. Also with the above reply, have the field show "0" vs being blank on records without any attachments. Thanks!

      Delete
  10. Sunil Sharma, very helpful indeed, just used your code to count attachments on more then 5 custom objects in managed package. Brilliant work. Thanks

    ReplyDelete
  11. how to get the count of attachments on an object using SOSL ?

    ReplyDelete
  12. Thx Sunil. If we were to do a trigger for Files this way - would it work?

    ReplyDelete
    Replies
    1. Figured it out ... just had to replace Attachment with 'ContentDocumentLink' and parentid with 'LinkedEntityId'

      Delete
    2. Do you have test class for it? Could you share it with me?

      Delete
  13. Can we write this same for Lighitning Upload files.

    ReplyDelete
  14. hi, I tried your code for counting attachments in Case object.
    i get bellow error:

    Error: Compile Error: Invalid identifier ' '. Apex identifiers must start with an ASCII letter (a-z or A-Z) followed by any number of ASCII letters (a-z or A-Z), digits (0 - 9), '$', '_'. at line 4 column 1

    ReplyDelete
  15. hi, I tried your code for counting attachments in Case object.
    i get bellow error:

    Error: Compile Error: Invalid identifier ' '. Apex identifiers must start with an ASCII letter (a-z or A-Z) followed by any number of ASCII letters (a-z or A-Z), digits (0 - 9), '$', '_'. at line 4 column 1

    please help me as I am new to APEX.

    ReplyDelete
  16. هل تبحث عن شركة متخصصة فى خدمات التنظيف بالطائف بافضل المعدات والسوائل وثقة تمة فى العمل ودقة فى النتائج كل هذه المميزت توفرها شركة الخليج الشركة الافضل والامثل فى الخدمات المنزلية بالطائف وبما اننا الشركة الافضل والامثل بدون منافس سوف نسعى لتوفر افضل الخدمات باقل تكلفة وبقدر كبير من الاهتمام والدقة عزيزى اينما كنت فى اى منطقة ا وحى تابع لمدينة الطائف اتصل بنا وسوف نصلك فى الحال شركة الخليج للخدمات المنزلية شركة تنظيف منازل بالطائف
    شركة تنظيف فلل بالطائف
    شركة تنظيف خزانات بالطائف
    شركة تسليك مجارى بالطائف
    شركة رش مبيدات بالطائف
    شركة مكافحة نمل ابيض بالطائف
    شركة مكافحة حشرات بالطائف
    شركة عزل اسطح بالطائف
    شركة عزل خزانات بالطائف

    ReplyDelete
  17. هل تبحث عن شركة متخصصة فى خدمات التنظيف بالطائف بافضل المعدات والسوائل وثقة تمة فى العمل ودقة فى النتائج كل هذه المميزت توفرها شركة الخليج الشركة الافضل والامثل فى الخدمات المنزلية بالطائف وبما اننا الشركة الافضل والامثل بدون منافس سوف نسعى لتوفر افضل الخدمات باقل تكلفة وبقدر كبير من الاهتمام والدقة عزيزى اينما كنت فى اى منطقة ا وحى تابع لمدينة الطائف اتصل بنا وسوف نصلك فى الحال شركة الخليج للخدمات المنزلية شركة تنظيف منازل بالطائف
    شركة تنظيف فلل بالطائف
    شركة تنظيف خزانات بالطائف
    شركة تسليك مجارى بالطائف
    شركة رش مبيدات بالطائف
    شركة مكافحة نمل ابيض بالطائف
    شركة مكافحة حشرات بالطائف
    شركة عزل اسطح بالطائف
    شركة عزل خزانات بالطائف

    ReplyDelete
  18. هل تبحث عن شركة متخصصة فى خدمات التنظيف بالطائف بافضل المعدات والسوائل وثقة تمة فى العمل ودقة فى النتائج كل هذه المميزت توفرها شركة الخليج الشركة الافضل والامثل فى الخدمات المنزلية بالطائف وبما اننا الشركة الافضل والامثل بدون منافس سوف نسعى لتوفر افضل الخدمات باقل تكلفة وبقدر كبير من الاهتمام والدقة عزيزى اينما كنت فى اى منطقة ا وحى تابع لمدينة الطائف اتصل بنا وسوف نصلك فى الحال شركة الخليج للخدمات المنزلية شركة تنظيف منازل بالطائف
    شركة تنظيف فلل بالطائف
    شركة تنظيف خزانات بالطائف
    شركة تسليك مجارى بالطائف
    شركة رش مبيدات بالطائف
    شركة مكافحة نمل ابيض بالطائف
    شركة مكافحة حشرات بالطائف
    شركة عزل اسطح بالطائف
    شركة عزل خزانات بالطائف

    ReplyDelete
  19. Past just words from administrators just as business experts, Salesforce has been chosen as a pioneer in the 'endeavor application stage as an administration' for the second sequential year by Gartner. salesforce for nonprofits

    ReplyDelete
  20. I am happy to find this post Very useful for me, as it contains lot of information. I Always prefer to read The Quality and glad I found this thing in you post. Thanks ソンウルナンバーおすすめい

    ReplyDelete
  21. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article. Vistara customer care

    ReplyDelete
  22. The Salesforce online training not only includes new functionalities and features of process builder, visual workflow, mobile and lightning but, also involves DEV 401 concepts Salesforce training in Chennai

    ReplyDelete

Governor Limits Example-Too Many DML Statements :151

Governor Limits Example : Too Many DML Statements :151 (Sunil Sharma) Example:Code Hitting Governor Limits System.LimitExceptio...