Skip to main content
Hi! I am trying to write a trigger to update a field on a custom object when an attachment is uploaded. My object is called Customer_Attachments__c and it has the field Attachment_IDs__c which is a list of attachment IDs: each time an attachment is uploaded, the attachment ID should be added to that list. But it's not working: it only adds the attachment ID after I click the Edit button on the record and click Save, but I want the ID to be added right away when the attachment is uploaded. I've tried copying the exact code from these similar posts https://developer.salesforce.com/forums/?id=906F00000008yrFIAQ and https://salesforce.stackexchange.com/questions/51532/trigger-updating-hyperlink-field-on-attachment-parent-record but it hasn't worked. 

My trigger looks like this:

trigger attachmentTrigger on Attachment (after insert) {

List<Customer_Attachments__c> ca = [SELECT Id, Attachment_IDs__c FROM Customer_Attachments__c WHERE Id=:trigger.new[0].parentId];

if(ca.size() > 0){

ca[0].Attachment_IDs__c = trigger.new[0].Id;

update ca;

}

}

It would be an added bonus if there was a way to add commas between the IDs, since right now it's just one long string.

Thanks!
5 answers
  1. Mar 18, 2021, 7:20 PM
    Hi Victoria,

    Try the below Trigger:

     

    trigger attachmentTrigger on Attachment (after insert) {

    set<Id> parentIdSet = new set<Id>();

    List<Customer_Attachments__c> updateParList = new List<Customer_Attachments__c>();

    Map<Id,List<Id>> idMap = new Map<Id,List<Id>>();

    for(Attachment a : trigger.New){

    parentIdSet.add(a.parentId);

    }

    if(!parentIdSet.isEmpty()){

    for(Attachment att : [select Id,ParentId from attachment where ParentId IN: parentIdSet]){

    if(!idMap.containsKey(att.ParentId)){

    idMap.put(att.ParentId, new List<Id>{att.id});

    }

    else{

    idMap.get(att.ParentId).add(att.Id);

    }

    }

    for(Id ids : idMap.keySet()){

    List<Id> idList = idMap.get(ids);

    Customer_Attachments__c acc = new Customer_Attachments__c( Id = ids, Attachment_IDs__c = string.join(idList, ','));

    updateParList.add(acc);

    }

    if(!updateParList.isEmpty()){

    update updateParList;

    }

    }

    }

    Thanks,

    Maharajan.C​​​​​​​

     
0/9000