Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 11 down vote accepted

This is possible, but in a rather roundabout way. There's no way to tell from a Schema.SObjectType or Schema.SObjectDescribeResult, but there is a slightly obscure method on Schema.DescribeFieldResult that can help: getReferenceTo();

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 contains method.

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.

share|improve this answer
    
It's not that obscure. I use it all the time. –  sfdcfox Apr 25 at 23:44
2  
I've downgraded it's obscurity from "rather" to "slightly". –  ca_peterson Apr 25 at 23:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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