Tag: Dynamic Apex

Apex: How to Dynamically Tell if a Salesforce Field Exists

How to Dynamically Tell if a Salesforce Field Exists

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;
    }