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
baseballkylebaseballkyle 

trigger for counting attachments on opportunity?

has anyone come across (or know how to build) a trigger for counting the # of attachments on an opportunity?

 

I did some research and found one post (http://goo.gl/jZlGC) - but that trigger does not work unfortunately....

 

Here is the trigger. Any ideas on what needs to be done to resolve?

 

It casuses this error:

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


 

trigger OpportunityAttachments on Attachment(after insert)

{

 List<Opportunity> oppListToBeUpdated = new List<Opportunity>();

 Map<ID,Integer> attachmentOppList = new Map<ID,Integer>();



 for(Attachment a: Trigger.new)

 {

 String parentIdval = a.parentid;

 if(parentIdval.startswith('006'))

 {

 if(attachmentOppList.get(a.parentid) == null)

 attachmentOppLIst.put(a.parentid, 0);

 else

 {

 Integer i = attachmentOppLIst.get(a.parentid);

 attachmentOppLIst.put(a.parentid, (i+1)); 

 }

 }

 }

 

 if(attachmentOppLIst.size() > 0)

 {

oppListToBeUpdated = [select id, Attachment_Count__c from Opportunity where id in :attachmentOppLIst.keyset()];

 for(Opportunity o: oppListToBeUpdated)
 {
   if(o.Attachment_Count__c != null)
    o.Attachment_Count__c = (Integer)attachmentOppLIst.get(o.id);
  else
  o.Attachment_Count__c = o.Attachment_Count__c + (Integer)attachmentOppLIst.get(o.id);//assuming that Attachment_Count__c is a numeric field.if not convert it to integer and add the value
 }
 }


 

 if(oppListToBeUpdated.size() > 0) 

 update oppListToBeUpdated;



}
AmitSahuAmitSahu

may be you are trying to fire the trigger on an opportunity without an attachment. try using try catch  block for avoiding errors..

 

Please let me know if this was not clear.

baseballkylebaseballkyle

nada, unfortunately. my test opp has 2 attachments. but thanks for the catch block suggestion.

kiranmutturukiranmutturu

intially set the field o.Attachment_Count__c  value to 0 then try to add

o.Attachment_Count__c = o.Attachment_Count__c + (Integer)attachmentOppLIst.get(o.id);

baseballkylebaseballkyle

could you elaborate a bit? the Attachment_Count__c field is a number field that is defaulted to 0. is there something else that needs to be done in the trigger beyond this or what? thanks!

 

Kyle