Schema Class in Salesforce Apex

In Salesforce Apex, properly organizing database objects, fields, and relationships is required to build easily maintainable applications. For this, we use the Schema Class in Apex, which provides methods to get details about database objects and fields.

In this tutorial, I will explain the Schema class in Salesforce Apex, how it works, and some practical ways you can use its methods.

What is Schema Class in Salesforce Apex?

In Salesforce Apex, the Schema Class is a built-in class that gives us access to metadata information. Using the Schema Class, we can access information about standard and custom objects, their fields, and their relationships in the Salesforce database. With the Schema class, we can describe objects, fields, and relationships without hardcoding them.

When to Use the Schema Class in Salesforce Apex

In Salesforce Apex, the schema class is helpful in scenarios where we need to retrieve information about objects and fields dynamically or when we have to build solutions that update automatically to changes in metadata, such as SOQL queries, Custom Validation rules, and field validation.

Below are the key features of the Apex schema class.

  • Describe Information: The Schema class gives access to metadata for Salesforce objects.
  • Dynamic Querying: We can write dynamic SOQL (Salesforce Object Query Language) queries using Schema methods.
  • Data Model Flexibility: It allows us to build adaptable, scalable solutions without knowing the structure of the data.

Key Components of Schema Class in Apex

In Apex, the Schema namespace contains several useful classes and methods, as mentioned below.

  • Schema.getGlobalDescribe(): This method retrieves a map of all objects in the Salesforce organization, including standard and custom objects.
  • Schema.SObjectType(): It represents a specific object and allows you to retrieve details about the object’s fields, record types, and other information.
  • Schema.SObjectField(): This method represents a field on an object and allows us to access properties such as data type, length, and label.
  • Schema.DescribeSObjectResult(): This function retrieves metadata about an object, such as its name, label, and fields.
  • Schema.DescribeFieldResult(): It provides metadata about a specific field, such as label, type, and whether it’s required.

Use Cases of Schema Classes in Salesforce Apex

Now, we will see the use cases of schema classes mentioned above in Salesforce Apex, with some practical examples.

1. Schema.getGlobalDescribe():

Following the below Apex code, we will retrieve all the objects in the organization using the Schema.getGlobalDescribe() method.

Map<String, Schema.SObjectType> allObjects = Schema.getGlobalDescribe();

for (String objName : allObjects.keySet()) {
    System.debug('Object Name: ' + objName);
}

Output:

get Global describe Schema method in Salesforce Apex

Now, we can see in the output that the schema class method Schema.getGlobalDescribe() retrieved and displayed all the objects in the debug output.

2. Schema.SObjectType():

In the Apex code, we will retrieve all fields of the Account object using the Schema.SObjectType() method.

Map<String, Schema.SObjectField> fieldsMap = Schema.SObjectType.Account.fields.getMap();

for (String fieldName : fieldsMap.keySet()) {
    System.debug('Field Name: ' + fieldName);
}

In the above code, we have also used the getMap() method, which returns a map of the fields, with each entry having the field’s API name as the key and a Schema.SObjectField object as the value.

Output:

Schema sobject method in Salesforce Apex

3. Schema.SObjectField():

Now, using the Schema.SObjectField() method, we will create a class to check if a field is required, accessible, or createable in the contact object. This can be useful for validations and dynamic form generation.

Schema.SObjectField contactEmailField = Contact.Email;
Schema.DescribeFieldResult fieldResult = contactEmailField.getDescribe();

System.debug('Is Field Required? ' + fieldResult.isNillable());
System.debug('Is Field Createable? ' + fieldResult.isCreateable());
System.debug('Is Field Accessible? ' + fieldResult.isAccessible());
Check Field Accessibility using Apex in Salesforce

4. Schema.DescribeFieldResult():

Now, we will try to get metadata about specific fields, such as their data type and length, using the Schema.DescribeFieldResult() method.

Schema.SObjectField accountNameField = Account.Name;
Schema.DescribeFieldResult fieldResult = accountNameField.getDescribe();

System.debug('Field Label: ' + fieldResult.getLabel());
System.debug('Field Type: ' + fieldResult.getType());
System.debug('Field Length: ' + fieldResult.getLength());
Schema class methods in Salesforce Apex

5. Using Schema for Dynamic SOQL Queries

In the Apex code below, we will write the SOQL query to retrieve all fields from the Account object rather than hardcoding specific field names.

Map<String, Schema.SObjectField> fieldsMap = Schema.SObjectType.Account.fields.getMap();
String query = 'SELECT ';

for (String fieldName : fieldsMap.keySet()) {
    query += fieldName + ', ';
}
query = query.substring(0, query.length() - 2) + ' FROM Account';
List<Account> accounts = Database.query(query);
System.debug('Accounts: ' + accounts);

Schema.SObjectType.Account.fields.getMap() retrieves a map of all fields for the Account object.

Using Schema for Dynamic SOQL Queries in Salesforce

We have used Schema.SObjectType.Account.fields.getMap() retrieves a map of all fields for the account object.

The getMap() method provides a map whose keys are the field names and values are objects representing field metadata.

The keySet() method’s returned set contains all the keys to iterate over the map’s entries.

This way, we can use the Schema methods in Salesforce to write dynamic SOQL queries.

Conclusion

In this Salesforce tutorial, we learned about Schema Classes and their use cases in Salesforce Apex. By now, you might have understood the Schema class methods we discussed in the above steps for different scenarios and use cases.

By using the Schema Class methods we have discussed, you can write classes that can dynamically access metadata, create flexible queries, and reduce hard coding.

You may also like to read.

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.