Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- trigger count_attachements on Attachment (after insert, after update, after delete, after undelete) {
- Set<Id> parentIdsSet = new Set<Id>(); //stores the parentids linked with modified attachments
- List<Attachment> attachmentList = new List<Attachment>(); //stores the list of modified attachments
- if (Trigger.new != null) {
- attachmentList.addAll(Trigger.new);
- } else if (Trigger.old != null){
- attachmentList.addAll(Trigger.old);
- }
- for (Attachment at: attachmentList) {
- parentIdsSet.add(at.ParentId);
- }
- parentIdsSet.remove(null);
- //stores mapping parentIds to total attachment count for that id
- Map<Id, Integer> objecttIdToAttachmentCount = new Map<Id, Integer>();
- for(AggregateResult ar: [SELECT count(Id) attachmentCount, parentId FROM Attachment WHERE parentId IN :parentIdsSet GROUP BY parentId]) {
- Id objId = (Id)ar.get('parentId');
- Integer count = (Integer)ar.get('attachmentCount');
- count = count == null ? 0 : count;
- objecttIdToAttachmentCount.put(objId, count);
- }
- //for cases where parentid's last attachment is deleted as the above SOQL query wont include the deleted attachments
- for(Id parentId: parentIdsSet) {
- if(!objecttIdToAttachmentCount.containsKey(parentId)) {
- objecttIdToAttachmentCount.put(parentId, 0);
- }
- }
- // not necessary but useful if multiple object types in the parent list
- Map<String, String> sobjectNameToTargetField = new Map<String, String> {
- 'Assignement__c' => 'Count_Attachment__c'
- };
- List<SObject> parentRecordsToUpdate = new List<SObject>();
- for (Id parentId: objecttIdToAttachmentCount.keySet()) {
- SObjectType currentType = parentId.getSObjectType();
- if(!sobjectNameToTargetField.containsKey(currentType.getDescribe().getName())) {
- continue;
- }
- SObject parent = currentType.newSObject();
- parent.put(sobjectNameToTargetField.get(currentType.getDescribe().getName()), objecttIdToAttachmentCount.get(parentId));
- parentRecordsToUpdate.add(parent);
- }
- parentRecordsToUpdate.sort();
- update parentRecordsToUpdate;
- }
Add Comment
Please, Sign In to add comment