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
vinothvinoth 

Trigger for bulk insertion on Attachments.

I wrote one trigger code on attachments. It will enable one check box in parent object if we add new attachments. Please find below code. It is working fine but when we do bulk insertion it’s not working fine. What mistake i did? How can i promote for bulk insertion also?

 

Parent object :Material__c

Parent Object field: Attachment_Exist__c(Check Box)

 

trigger TriggerOnAttachments on Attachment (after insert) {

List<Material__c> msd2 = [select id, Attachment_Exist__c from Material__c where id =: Trigger.New[0].ParentId];

                        if(msd2.size()>0)
                        {
                                    msd2[0].Attachment_Exist__c = true;
                                    update msd2;
                        }                      
}
Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

You are only checking the first element in the list passed in to the trigger.

 

You'll need to iterate the records to build the list of parent ids, then pull back all of those.  Off the top of my head:

 

List<Id> parentIds=new List<Id>();
for (Attachment att : trigger.new)
{
   parentIds.add(att.ParentId);
}

List<Material__c> msd2 = [select id, Attachment_Exist__c from Material__c where id in :parentIds];

if(msd2.size()>0) 
{
   for (Material__c msd : msd2)
   {
      msd.Attachment_Exist__c = true;
   }
   update msd2;
}                      

 

 

 

All Answers

bob_buzzardbob_buzzard

You are only checking the first element in the list passed in to the trigger.

 

You'll need to iterate the records to build the list of parent ids, then pull back all of those.  Off the top of my head:

 

List<Id> parentIds=new List<Id>();
for (Attachment att : trigger.new)
{
   parentIds.add(att.ParentId);
}

List<Material__c> msd2 = [select id, Attachment_Exist__c from Material__c where id in :parentIds];

if(msd2.size()>0) 
{
   for (Material__c msd : msd2)
   {
      msd.Attachment_Exist__c = true;
   }
   update msd2;
}                      

 

 

 

This was selected as the best answer
vinothvinoth

Thanks. It’s working well. Please tell me, how to check whether the attachments present or not for particular record? Is there any flag value available to find these attachments? I am writing code by getting attachments count (ie,.0 or greater than 0). Is this correct?

bob_buzzardbob_buzzard

There's no standard flag available. I've handled this in the past by creating a custom field on the object and then populating that via a trigger when an attachment is uploaded.