In the previous article we have learned about How to Fetch API Names of All Fields for an Object Using Dynamic Apex in Salesforce which you can read from here. In this article I will tell you How to fetch all fields of Field Sets using Dynamic Apex in Salesforce?
In this article, we will look at a code example that demonstrates How to fetch all fields of Field Sets using Dynamic Apex in Salesforce?
Below is the code snippet which will fetch all fields of Field Sets of Account object.
// Retrieve a map of all Field Sets for the Account object, where the key is the Field Set API name. Map<String, Schema.FieldSet> FsMap = Schema.SObjectType.Account.fieldSets.getMap(); // Get a set of all Field Set names (keys) from the map. Set<String> keys = FsMap.keySet(); // Iterate through each Field Set in the Account object. for (String key : keys) { // Retrieve the name of the Field Set. String fieldSetName = FsMap.get(key).getName(); System.debug('Field Set Name: ' + fieldSetName); // Retrieve the Field Set metadata using its name. Schema.FieldSet fieldSet = Schema.SObjectType.Account.fieldSets.getMap().get(fieldSetName); // Get the list of fields (FieldSetMembers) associated with the Field Set. List<Schema.FieldSetMember> fieldSetMembers = fieldSet.getFields(); // Iterate through each field in the Field Set. for (Schema.FieldSetMember fieldSetMember : fieldSetMembers) { // Log the field's label (user-friendly name). System.debug('Field Label ====> ' + fieldSetMember.getLabel()); // Log the field's API name (used in Apex and integrations). System.debug('Field API Name ====> ' + fieldSetMember.getFieldPath()); } // Separator for readability in debug logs. System.debug('----------------'); }
Let’s try to understand the code step-by-step:
- Line 1: Retrieve a map of all Field Sets for the
Account
object.- Key: Field Set API name.
- Value: Corresponding
Schema.FieldSet
metadata.
- Line 2: Get all Field Set names as a
Set<String>
from the map. - Lines 3-17: Iterate through each Field Set:
- Line 5: Get the Field Set Name using
.getName()
and log it. - Line 7: Retrieve the
FieldSet
metadata using its name. - Line 9: Get a list of all fields inside the Field Set using
.getFields()
. - Lines 11-15: Loop through each field (
FieldSetMember
):- Line 13: Log the Field Label (user-friendly name).
- Line 15: Log the Field API Name (used in Apex/integrations).
- Line 17: Adds a separator (
System.debug('----------------');
) for better log readability.
- Line 5: Get the Field Set Name using
Also, check out the below video on How to fetch all fields of field sets using apex in Salesforce?
We hope now you know How to fetch all fields of Field Sets using Dynamic Apex in Salesforce. If you have any doubts then let us know in the comment box below.