Skip to content

Instantly share code, notes, and snippets.

@mhamzas
Last active March 29, 2019 09:29
Show Gist options
  • Save mhamzas/cb8b6ce3b0a388134d57234df30fe113 to your computer and use it in GitHub Desktop.
Save mhamzas/cb8b6ce3b0a388134d57234df30fe113 to your computer and use it in GitHub Desktop.
Apex Trigger to move Attachment from Task to Parent
//
// Author : M Hamza Siddiqui
// Created Date : 9/14/2018
// Description : Apex Trigger to move Attachment from Task to Parent Object Record (on the basis of WHATID i.e. RelatedTo)
//
// Initializing Trigger when any new attachment get inserted in SF
trigger AttachtoParent on Attachment (after insert) {
List<Attachment> Attachments = new list<Attachment>();
// Looping thorugh the attachments
for (Attachment a : trigger.new){
Attachments.add(a);
}
if(Attachments !=null && Attachments.size() > 0 ){
AttachtoParent_Handler att = new AttachtoParent_Handler(Attachments);
}
}
public class AttachtoParent_Handler {
public AttachtoParent_Handler(List<Attachment> Attach){
if(Attach != null && Attach.size() > 0){
for (Attachment a : Attach){
String parentIdString = String.valueof(a.parentId);
// Making sure if the attachment is from the Task
if (parentIdString.substring(0,3) == '00T'){
// Getting Parent Object Id
task parent = [SELECT Id,WhatId FROM Task WHERE Id = :a.parentId];
if (parent.WhatId != null){
Attachment body = [SELECT Body FROM Attachment WHERE Id = :a.Id];
// Adding same attachment to Parent Object Record Id.
Attachment newA = New Attachment(
Name = a.Name,
Body = body.Body,
OwnerId = a.OwnerId,
ParentId = parent.WhatId
);
insert newA;
}
}
}
}
}
}
@isTest
public class AttachtoParent_Handler_Test {
static testMethod void testAttachments()
{
Task task=new Task();
insert task;
Attachment attach=new Attachment();
attach.Name='Unit Test Attachment';
Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
attach.body=bodyBlob;
attach.parentId=task.id;
insert attach;
List<Attachment> attachments=[select id, name from Attachment where parentId=:task.Whatd];
System.assertEquals(1, attachments.size());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment