daily pastebin goal
3%
SHARE
TWEET

Untitled

a guest Jan 21st, 2019 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. trigger count_attachements on Attachment (after insert, after update, after delete, after undelete) {
  2.     Set<Id> parentIdsSet = new Set<Id>(); //stores the parentids linked with modified attachments
  3.     List<Attachment> attachmentList = new List<Attachment>(); //stores the list of modified attachments
  4.  
  5.     if (Trigger.new != null) {
  6.         attachmentList.addAll(Trigger.new);
  7.     } else if (Trigger.old != null){
  8.         attachmentList.addAll(Trigger.old);
  9.     }
  10.  
  11.     for (Attachment at: attachmentList) {
  12.         parentIdsSet.add(at.ParentId);
  13.     }
  14.  
  15.     parentIdsSet.remove(null);
  16.  
  17.     //stores mapping parentIds to total attachment count for that id
  18.     Map<Id, Integer> objecttIdToAttachmentCount = new Map<Id, Integer>();
  19.  
  20.     for(AggregateResult ar: [SELECT count(Id) attachmentCount, parentId FROM Attachment WHERE parentId IN :parentIdsSet GROUP BY parentId]) {
  21.         Id objId = (Id)ar.get('parentId');
  22.         Integer count = (Integer)ar.get('attachmentCount');
  23.  
  24.         count = count == null ? 0 : count;
  25.         objecttIdToAttachmentCount.put(objId, count);
  26.     }
  27.  
  28.     //for cases where parentid's last attachment is deleted as the above SOQL query wont include the deleted attachments
  29.     for(Id parentId: parentIdsSet) {
  30.         if(!objecttIdToAttachmentCount.containsKey(parentId)) {
  31.             objecttIdToAttachmentCount.put(parentId, 0);
  32.         }
  33.     }
  34.  
  35.     // not necessary but useful if multiple object types in the parent list    
  36.     Map<String, String> sobjectNameToTargetField = new Map<String, String> {
  37.         'Assignement__c' => 'Count_Attachment__c'
  38.     };
  39.  
  40.     List<SObject> parentRecordsToUpdate = new List<SObject>();
  41.  
  42.     for (Id parentId: objecttIdToAttachmentCount.keySet()) {
  43.         SObjectType currentType = parentId.getSObjectType();
  44.  
  45.         if(!sobjectNameToTargetField.containsKey(currentType.getDescribe().getName())) {
  46.             continue;
  47.         }
  48.  
  49.         SObject parent = currentType.newSObject();
  50.         parent.put(sobjectNameToTargetField.get(currentType.getDescribe().getName()), objecttIdToAttachmentCount.get(parentId));
  51.  
  52.         parentRecordsToUpdate.add(parent);
  53.     }
  54.  
  55.     parentRecordsToUpdate.sort();
  56.     update parentRecordsToUpdate;
  57.  
  58. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top