You need to sign in to do that
Don't have an account?
SGul
Attachment Parent Name not directly accessible in After Insert/After Update Trigger.
Hi, I have written a trigger on Attachment (after insert, after update) I am trying to fetch the Parent Name in that by following code. Anyone having idea why reference field's data is not accessible in trigger? for(attachment a: trigger.new) { system.debug(a.ParentId) ; //It returns the ID appropriately system.debug(a.Parent.Name); //but this is returning null even when corresponding name field is having data. system.debug(a.Parent); //even this is being returned as null; } There can be attachments related to n number of objects. I don't want to fire too many SOQL just to know to which Parent this attachment is referring to. Can anyone please suggest workaround for it? Thanks |
You can use a child to parent relationship query to pull back the name of the parent.
Something like:
All Answers
This is because attachment.Parent is a related object. The ParentId is filled in as this is a field on the attachment record. If you want to access any of the fields on the parent object, you will need to query that back via a SOQL statement.
When a record goes through a trigger, it doesn't contain the full object graph with parent/children populated.
Thanks Bob for your reply,
But my concern is -- attachments can relate to account, contact , opportunity ...n number of objects.
I can't write so many queries just to figure it out to which object this attachment belongs to.
For Example
If in my application i am expecting to get attachments in 10 objects. I will have to fire 10SOQL just to figure out to which object it belongs to, which is not possible
since tomorrow there can be requiremnt that we will get attachment related to one new object. In that case i will have to write one more SOQL in trigger corres to that???
is there any alternative way for it rather than firing SOQL??
You can use a child to parent relationship query to pull back the name of the parent.
Something like:
Thanks Bob.. :)
I wonder i was writing this query in Systm log to check whether its returning proper records but why din't i think of writing it in Trigger :)
probably din't want to fire a SOQL there :)
Now i have written following code and its working fine :)
for(Attachment objAttach : [Select ID,Body, BodyLength, ContentType,CreatedById,CreatedDate,Description,IsPrivate,LastModifiedById,LastModifiedDate,Name,OwnerId,ParentId, Parent.Name,SystemModstamp from attachment where id in: trigger.newMap.keySet()])
{
/ /accessed Parent name here
}
Prepare MAP for parentid and parentname, outside/before main loop and use map as parentname lookup inside loop.