top of page

How to get FieldSet fields in Apex Dynamically

Salesforce FieldSets are very useful to define custom layouts in Apex Class, Lightning components and Lightning Web Components

It Supports both Standard and Custom Objects of Salesforce

FieldSets can be accessed through Apex Class

Schema.FieldSet contains all the fields from the FieldSet , lets see the below example

public static List<Schema.FieldSetMember> readFieldSet(String fieldSetName, String ObjectName)
    Map<String, Schema.SObjectType> GlobalDescribeMap = Schema.getGlobalDescribe(); 
    Schema.SObjectType SObjectTypeObj = GlobalDescribeMap.get(ObjectName);
    Schema.DescribeSObjectResult DescribeSObjectResultObj = SObjectTypeObj.getDescribe();
Schema.FieldSet fieldSetObj = DescribeSObjectResultObj.FieldSets.getMap().get(fieldSetName);
return fieldSetObj.getFields(); 

Schema.FieldSetMember contains fieldApiName , Label , Data Type and Other properties of field from FieldSet. Let's see an Example to read fields from field-set

List<Schema.FieldSetMember> fieldSetMemberList =  Util.readFieldSet('Account_FieldSet','Account');
for(Schema.FieldSetMember fieldSetMemberObj : fieldSetMemberList)
    system.debug('API Name ==>' + fieldSetMemberObj.getFieldPath()); //api name
    system.debug('Label ==>' + fieldSetMemberObj.getLabel());
    system.debug('Required ==>' + fieldSetMemberObj.getRequired());
    system.debug('DbRequired ==>' + fieldSetMemberObj.getDbRequired());
    system.debug('Type ==>' + fieldSetMemberObj.getType());   //type - STRING,PICKLIST
1,337 views2 comments
bottom of page