You need to sign in to do that
Don't have an account?
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; }
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.
nada, unfortunately. my test opp has 2 attachments. but thanks for the catch block suggestion.
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);
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