Lately, I’ve been working on a lot of dynamic apex and soql. I had a requirement to develop a custom appexchange app that could be dynamically querying objects based on a mapping that the admin had supplied and had stored in custom settings.
Originally, I was querying to see if the field existed and returning true if a result was received but this ended taking a lot longer than doing a describe.
I wasn’t able to find any information on how to really tell if a field exists or not. Without further ado, doesFieldExist will return true if the object and field both exist. If the object has been removed and the code hasn’t caught that it will also return false. And finally, if the object exists but the field doesn’t it will return false.
public boolean doesFieldExist(String objName, string fieldName) { try { SObject so = Schema.getGlobalDescribe().get(objName).newSObject(); return so.getSobjectType().getDescribe().fields.getMap().containsKey(fieldName); } catch(Exception ex) {} return false; }
3 responses to “Apex: How to Dynamically Tell if a Salesforce Field Exists”
Hello ,
I want to write some SOQL query for enable Quotes.
When I install package, At that time i want to check Quotes (Standard Object – Salesforce) enable or not.
If not enable,I want to enable it in Post Install Script. Is it possible?
Doesn’t seem to be.
I cant find a way to tell if it’s enabled or not.
You have to use the Metadata API to enable Quotes if the feature is not already enabled.
https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_quotessettings.htm
Check out the metadata api apex library by financialforce, https://github.com/financialforcedev/apex-mdapi, which will aid in trying to do some from apex. However, to do this may not be possible except via a post-install script from your package which may be too late in the installation process as your code likely needed Quotes to already be enabled for your components to be deployed.
Worst case, add that enabling quotes is a pre-requisite to installing your package.