Apex: How to Dynamically Tell if a Salesforce Field Exists

Sharing is Caring

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

Sharing is Caring

Brian is a programmer and technology leader living in Niagara Falls with more than ten years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.

3 Comments

  1. Bhavesh Jogi

    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?

Comments are closed.