首页 > 解决方案 > 字段更改时将附件从父对象复制到子对象

问题描述

尝试在机会(父对象)上插入附件时将附件从父对象复制到子对象

我试过写一些代码。

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;   

    }

}

每次附件都附加到 Opportunity 时……它对我不起作用!

标签: salesforceapexsfdc

解决方案


ruMap的密钥由EIP_Lead_Rental_Object__cid 制成。但是您尝试get()使用 Opportunity Id 调用它。这永远不会奏效。我很惊讶它没有给你抛出一个与 null 相关的错误,你那里有一些 try-catch 可以吞下异常吗?

你可能需要类似的东西

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);
}

然后你可以

for(Attachment file : Trigger.new){
    if(ruMap.containsKey(file.ParentId)){
        Attachment newFile = file.clone();
        newFile.ParentId = ruMap.get(file.ParentId).Id;
        attachments.add(newFile);
    }
}

推荐阅读