I have some apex that generates a PDF and tries to attach it to a custom object type that the user defines.
One issue I have with this is that if the type doesn’t support notes and attachments this fails, but I don’t really know that until after I already went to the trouble of generating the attachment record and trying to save it – quite a waste of resources for an operation that’s clearly doomed to fail.
Is there any way to tell, at runtime in apex, if an SObjectType supports notes and attachments?
This is possible, but in a rather roundabout way. There’s no way to tell from a
Schema.SObjectDescribeResult, but there is a slightly obscure method on
Schema.DescribeFieldResult that can help:
Set<Schema.SObjectType> attachableTypes = new Set<Schema.SObjectType>( Schema.SObjectType.attachment.fields.parentId.getReferenceTo() ); System.debug(attachableTypes.contains(Account.SObjectType)); //true System.debug(attachableTypes.contains(Note.SObjectType)); //false
What I’m doing here is checking what types of records can be valid in the
attachment.parentId field. This returns a list, and there’s no efficient way to say “is my type in that big list”, so I’m building a Set for it’s
After that I can cache that set somewhere like a static variable an continue to reference it throughout my code as needed.
Bonus: The same idea can be applied to check if an SObject type supports tasks and events or not.