We have discussed that Schema class in Salesforce is really help you to solve your many issues , Schema class has many build in functions which helps you to write sort code .
Here are two ways to check if certain field is exist on Given object or not ! We are going to check if object has Name field . We know that some objects like : Task , Case do not have Name field .
Way 1 :
Map<String, Schema.SObjectType> describe = Schema.getGlobalDescribe();
Boolean ObjectHasCertainField = False;
Schema.DescribeFieldResult describeField;
for(Schema.SObjectField strFld :describe.get('Contact').getDescribe().fields.getMap().Values()) {
describeField = strFld.getDescribe();
if( describeField.getName() == 'Name' ) {
ObjectHasCertainField = true;
}
}
System.debug(ObjectHasCertainField);
Way 2 :
Map<String, Schema.SObjectType> s = Schema.getGlobalDescribe();
Boolean ObjectHasCertainField = s.get('Task').getDescribe().fields.getMap().keySet().contains('name');
System.debug('ObjectHasCertainField '+ ObjectHasCertainField);
These are the finest way to check if object has certain field or not . If you find any other solution then please post in comment section .
Watch the video for understanding code used in this post .
How the two ways work
Way 1 loops over every field of Contact and compares each field name with Name. Way 2 reads the field Map of Task and checks whether the key name exists. Task has no Name field, so Way 2 prints false.
Which way is better?
Way 2 is shorter and faster, because it checks the Map keys directly instead of describing every field. The keys of the field Map are lowercase API names, which is why the check uses name in lowercase.
Reusable method
public static Boolean fieldExists(String objectName, String fieldName) {
Schema.SObjectType objType = Schema.getGlobalDescribe().get(objectName);
return objType != null && objType.getDescribe().fields.getMap().containsKey(fieldName.toLowerCase());
}
System.debug(fieldExists('Contact', 'Name'));
System.debug(fieldExists('Task', 'Name'));The method also returns false when the object name is wrong, instead of throwing a null pointer error.
FAQ
Does it work for custom fields?
Yes. Pass the full API name, for example Student__c and Age__c.
Does the check show whether I can read the field?
No. It only checks that the field exists. Use isAccessible() on the field describe to check access.