Reputation: 1
Trying copying Attachments from parent object to child object when attachment gets inserted on Opportunity(Parent Obj)
I have tried writing some code.
trigger CopyAttachmentsToRU on Attachment (after insert) {
Set<Id> OppIds = new Set<Id>();
for(Attachment file : Trigger.new) {
// only collect those that are for the Opportunity object (others can be ignored)
if(file.ParentId.getSObjectType() == Opportunity.getSObjectType()) {
OppIds.add(file.ParentId);
system.debug(OppIds);
}
}
if(!OppIds.isEmpty()) {
Map<Id,EIP_Lead_Rental_Object__c> ruMap = new Map<Id,EIP_Lead_Rental_Object__c>([select EIP_Opportunity__c from EIP_Lead_Rental_Object__c where EIP_Opportunity__c in : OppIds]);
List<Attachment> attachments = new List<Attachment>();
system.debug(ruMap);
for(Attachment file : Trigger.new) {
Attachment newFile = file.clone();
newFile.ParentId = ruMap.get(file.ParentId).Id;
attachments.add(newFile);
}
// finally, insert the cloned attachments
insert attachments;
}
}
Every time an attachment gets attach to Opportunity..its not working for me !
Upvotes: 0
Views: 1951
Reputation: 19622
Your ruMap
has keys made out of EIP_Lead_Rental_Object__c
ids. But you try to call get()
on it using Opportunity Ids. This will never work. I'm surprised it doesn't throw you a null-related error, do you have some try-catch in there that just swallows the exception?
You probably need something like
Map<Id,EIP_Lead_Rental_Object__c> ruMap = new Map<Id,EIP_Lead_Rental_Object__c>();
for(EIP_Lead_Rental_Object__c obj : [select Id, EIP_Opportunity__c from EIP_Lead_Rental_Object__c where EIP_Opportunity__c in : OppIds]){
ruMap.put(obj.EIP_Opportunity__c, obj);
}
and then you can
for(Attachment file : Trigger.new){
if(ruMap.containsKey(file.ParentId)){
Attachment newFile = file.clone();
newFile.ParentId = ruMap.get(file.ParentId).Id;
attachments.add(newFile);
}
}
Upvotes: 1