How to check if SObject has certain field? check field exists or not on Object using Apex?

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 .

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top