function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Simon BairdSimon Baird 

Invalid id value for this SObject type - Trigger on attachment

Hi all,

I need some help with a trigger that attaches the date time to a field when an attachment is added to a custom object (patient__c). The trigger works fine when attaching a file to the patient record but when you try and attach a file to any other object it throws the error "Invalid id value for this SObject type"
Below is the trigger

trigger LastAttach on Attachment (After insert) {
    list<patient__c> ptlist= new  list<patient__c>() ;
    Patient__c ac= new Patient__c();
    for (attachment a : trigger.new ){
   
        ptlist.add( new Patient__c(Id=a.ParentID, Attachment_Added__c= System.now()));
   
            }
  //}
    update ptlist;
    }
Best Answer chosen by Simon Baird
Shingo YamazakiShingo Yamazaki
Sorry, please replace "id" with "parentId"

trigger LastAttach on Attachment (After insert) {
    list<patient__c> ptlist= new  list<patient__c>() ;
    Patient__c ac= new Patient__c();
    for (attachment a : trigger.new ){
        ID parentId = a.ParentID;
        if (parentId.getSObjectType() == Patient__c.sObjectType) {
            ptlist.add( new Patient__c(Id=a.ParentID, Attachment_Added__c= System.now()));
        }
    }
    update ptlist;
}


All Answers

Shingo YamazakiShingo Yamazaki
Dear Simon,

I'm Shingo.

You need to check if the type of ID is expected custom object.
So, how about this?

trigger LastAttach on Attachment (After insert) {
    list<patient__c> ptlist= new  list<patient__c>() ;
    Patient__c ac= new Patient__c();
    for (attachment a : trigger.new ){
        ID parentId = a.ParentID;
        if (id.getSObjectType() == Patient__c.sObjectType) {
            ptlist.add( new Patient__c(Id=a.ParentID, Attachment_Added__c= System.now()));
        }
    }
    update ptlist;
}


Simon BairdSimon Baird
Hi Shingo, Thanks for the help. I am getting an error “variable does not exist: id” with your updated code. Simon
Shingo YamazakiShingo Yamazaki
Sorry, please replace "id" with "parentId"

trigger LastAttach on Attachment (After insert) {
    list<patient__c> ptlist= new  list<patient__c>() ;
    Patient__c ac= new Patient__c();
    for (attachment a : trigger.new ){
        ID parentId = a.ParentID;
        if (parentId.getSObjectType() == Patient__c.sObjectType) {
            ptlist.add( new Patient__c(Id=a.ParentID, Attachment_Added__c= System.now()));
        }
    }
    update ptlist;
}


This was selected as the best answer
Simon BairdSimon Baird
Thanks Shingo its working now