Saturday, July 12, 2025

Understanding DescribeFieldResult in Apex with Real-Time Examples

In Salesforce Apex, the Schema.DescribeFieldResult class provides metadata about fields on standard and custom objects. This is especially useful when building dynamic applications that need to adapt to different field configurations or enforce field-level security.

To instantiate a DescribeFieldResult object, you can use the following syntax:

Schema.DescribeFieldResult dfr = Account.Description.getDescribe();

This retrieves metadata about the Description field on the Account object. Let’s explore some of the most useful methods available in DescribeFieldResult, with real-time examples for selected ones.

getPicklistValues()

Returns a list of active PicklistEntry objects for a picklist field.

Example:

Schema.DescribeFieldResult dfr = Account.Industry.getDescribe();

List<Schema.PicklistEntry> picklistValues = dfr.getPicklistValues();

for (Schema.PicklistEntry entry : picklistValues) {

    System.debug('Picklist Value: ' + entry.getLabel());

}

getSObjectType()

Returns the object type from which the field originates.

Example:

Schema.DescribeFieldResult dfr = Account.Name.getDescribe();

Schema.SObjectType objType = dfr.getSObjectType();

System.debug('Object Type: ' + objType.getDescribe().getName());

isAccessible()

Checks if the current user has visibility to the field.

Example:

Schema.DescribeFieldResult dfr = Contact.Email.getDescribe();

if (dfr.isAccessible()) {

    System.debug('User can access the Email field.');

} else {

    System.debug('User cannot access the Email field.');

}

isUpdateable()

Checks if the field can be edited by the current user.

Example:

Schema.DescribeFieldResult dfr = Opportunity.StageName.getDescribe();

if (dfr.isUpdateable()) {

    System.debug('User can update the StageName field.');

} else {

    System.debug('User cannot update the StageName field.');

}

Conclusion:

Using DescribeFieldResult methods allows developers to build smarter, more secure, and dynamic applications in Salesforce. Whether you're validating permissions, fetching picklist values, or inspecting field metadata, these tools are essential for robust Apex development.

No comments:

Post a Comment