+ Start a Discussion
ArrowArrow 

Trigger to count number of attachments on Opportunity

I am fairly new to triggers and need help writing the following trigger:

 

Update customer numeric field on opportunity with count of attachements when a new attachment added to the opportunity.

 

 

Ispita_NavatarIspita_Navatar

Hi,

Please try the following:-

trigger IncrementCountin Opportunity on Task (before insert, before update, after delete) {

if(trigger.isbefore)

{

// for insert

if(trigger.isInsert)

{

Task tk = trigger.new[0];

Opportinity Opp = [Select id, count from Opportunity where id: tk.whoid];

if (opp.size>0)

{

Opp.count= Opp.Count +1;

update opp;

}

}

 

// similarly you can put code for update

 

 

 

// for delete

 

if(trigger.isafter)

{

if(trigger.isdelete)

{

Task tk = trigger.old[0];

Opportinity Opp = [Select id, count from Opportunity where id: tk.whoid];

if (opp.size>0)

{

Opp.count= Opp.Count -1;

update opp;

}

}

 

 

 

 

 

}

}

Imran MohammedImran Mohammed

Hi,

 

Use the below code for counting attachments on opportunity.

 

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.contains('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, cust_no__c from Opportunity where id in :attachmentOppLIst.keyset()];

 for(Opportunity o: oppListToBeUpdated)

 {

 o.cust_no__c = o.cust_no__c + (Integer)attachmentOppLIst.get(o.id);//assuming that cust_no__c is a numeric field.if not convert it to integer and add the value

 }

 }

 

 if(oppListToBeUpdated.size() > 0) 

 update oppListToBeUpdated;


}

 

Let me know if you have any questions.

RagingForceRagingForce

try using btach apex and query NoteAndAttachment object. The issue here is how do you want to trigger batch, through a trigger or scheduler?

Trigger would probably be on opportunity, if using scheduler which i would recommend do it maybe once everyday?

Imran MohammedImran Mohammed

I am not sure whether i misunderstood the question.

The requirement as per the questioon was to count attachments on an opportunity when an attachment was added to opportunity.

ArrowArrow

Hi Imran, you understood exactly what I am looking for, thanks.

 

I managed to add your trigger to my developer account, amending the field name to match mine (see code below) but I am getting the below error, ideas?

 

Also could you help me with the test I need to write to get this into Production.

 

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 51, column 26
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.contains('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)

 {

 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;



}

 

RagingForceRagingForce

hmm imran i don't think you can create a trigger on attachment. the best thing he can do is use batch apex to look every day at all attachments on an opportunity create a map the opp id and count of attachments found then update all opps back.

RagingForceRagingForce

is attachment a custom object?

Imran MohammedImran Mohammed

Can you highlight whihc line is actually causing the error?

Imran MohammedImran Mohammed

Attachment is a standard object.

Imran MohammedImran Mohammed

Update the for loop code to this.

 

 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
 }
 }

 

Imran MohammedImran Mohammed

What is the type of Attachment_Count__c field?

Let me know if you face any issues.

RagingForceRagingForce

this is interesting where is the attachment object found in the setup area?

Imran MohammedImran Mohammed

You can see Attachment object when you use Force.com IDE.

Imran MohammedImran Mohammed

Instead of 

if(parentIdval.contains('006'))

change it to 

if(parentIdval.startswith('006'))

RagingForceRagingForce

i am wondering how google docs are attached it is not recognised as an attachment?

ArrowArrow

Hi Imran, thanks for your help

 

Field  Attachment_Count__c is a Number field with length 5, 0 decimal places   

 

 I have updated the trigger as below, have I got it right?

 

If I add an attachment normally, I get the below error message:

 

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 27
 
 Line 52 is :o.Attachment_Count__c = o.Attachment_Count__c + (Integer)attachmentOppLIst.get(o.id);
 
If I edit the field on the opportunity to zero rather than null, then I don't get an error but the field is not updated after adding an attachment, just remains zero!

 

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;



}

 

 

 

Imran MohammedImran Mohammed

Can you change the else part code to this and let me know what the debug values are?

else

{

system.debug(o.Attachment__c+'  Attachment val');

system.debug(attachmentOppLIst.get(o.id));

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

system.debug(o.Attachment__c+'  Attachment val after update');

 

}

ArrowArrow

Hi Imran, I am unable to save this code in Eclipse.

 

I get following error :

 

Severity and Description Path Resource Location Creation Time Id
Save error: Invalid field Attachment__c for SObject Opportunity Developer/src/triggers OpportunityAttachments.trigger line 55 1290690806841 222

Against this row:

 

system.debug(o.Attachment__c+

Also this is the first time I have used debug. Wondering what filters I should use?

Apex Code - Debug?

Thanks for your patience

Stefan

 

' Attachment val');

Imran MohammedImran Mohammed

Sorry, actually i meant o.Attachment_Count__c in the debug statement.

ArrowArrow

Not sure what I should be looking for in the Debug log?

 

There are so many rows. Are the two below the right ones?

 

15:18:16.184|WF_ACTION| Field Update: 1;
15:18:16.188|WF_ACTIONS_END| Field Update: 1;

ArrowArrow

Can anyone help me solve this?

Nicholas BrownellNicholas Brownell

This is a really old thread, but I tried was referencing it in order to add an attachment counter to a custom object and had no success. I eventually found something elsewhere I was able to use so I thought I would post my trigger in case anyone else came looking for an attachment counter. I also added the delete portion so the counter would be accurate with attachment removals, as well. If you se anything I neglected and should add, please let me know!

trigger EssayAttachmentCounter on Attachment (after insert, before delete) {

if(trigger.isinsert){        
List<TargetX_SRMb__Essay__c> co = [select id, Number_of_Attachments__c from TargetX_SRMb__Essay__c where id =: Trigger.New[0].ParentId];          
If(co.size()>0 && co[0].Number_of_Attachments__c != null)          
{              
co[0].Number_of_Attachments__c = co[0].Number_of_Attachments__c + 1;              
update co;          

If(co.size()>0 && co[0].Number_of_Attachments__c == null)          
{              
co[0].Number_of_Attachments__c = 1;              
update co;          

}

if(trigger.isdelete){
List<TargetX_SRMb__Essay__c> co = [select id, Number_of_Attachments__c from TargetX_SRMb__Essay__c where id =: Trigger.old[0].ParentId];          
If(co.size()>0)          
{              
co[0].Number_of_Attachments__c = co[0].Number_of_Attachments__c - 1;              
update co;          

}
}