0

When my Salesforce receives e-mails it will create a Case for it. I want the attachments from that case to be copied to my custom object "Case_Attachment__c".

I created a Apex Trigger for this:

trigger CaseAttachmentTrigger on Attachment  (after insert) {
    List<Case_Attachment__c> cons = new List<Case_Attachment__c>();
    for(Attachment a :trigger.new){
        Case_Attachment__c c  = new Case_Attachment__c();
        c.name = a.name;
        c.Attachment__c = a.id;
        c.Case__c = a.parentId;
        cons.add(c);
    }
    insert cons;
}

However I get this error:

caused by: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Case: id value of incorrect type: a1G25000000aL35EAE: [Case__c]

Trigger.CaseAttachmentTrigger: line 10, column 1

This is my custom fields:

  • Attachment Attachment__c Text(100)
  • Case Case__c Master-Detail(Case)
  • View View__c Formula (Text) _c Master-Detail(Case)
2
  • Are looking for attachment from the email to copied into your custom object ? When you configured email-to-case , sales-force will be creating case and email received will be attached into case record.
    – NITHESH K
    Jul 25 '18 at 12:04
  • NITHESH K: That is correct. I can see the attachment is being created to that emails, and that it has parent ID for the case.
    – Europa
    Jul 25 '18 at 12:30
1

The immediate error is that the parent object of the Attachment looks like it is a custom object not a Case object.

You need to remember that your trigger will run for any Attachment added to any type of object so you should be very careful about the logic so that it is only applied where it is relevant. (Getting this wrong for an object that is used by many different apps in an org can mean that you break those apps not just your own app.)

For example:

trigger CaseAttachmentTrigger on Attachment (after insert) {
    List<Case_Attachment__c> cons = new List<Case_Attachment__c>();
    for(Attachment a : Trigger.new) {
        // Ignore Attachments added to any other type of object
        if (a.ParentId.getSObjectType() == Case.SObjectType) {
            Case_Attachment__c c = new Case_Attachment__c(
                Name = a.Name,
                Attachment__c = String.abbreviate(a.Body, 100),
                Case__c = a.ParentId
            );
            cons.add(c);
        }
    }
    insert cons;
}

(It looks like Case_Attachment__c.Attachment__c is a text field not an Id field so I've changed that logic a bit too.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.