top of page
Search

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,457 views2 comments

2 Comments


Unknown member
Aug 10, 2021

I like this post , it is working as expected thank you so much for sharing. is there a way we can add field dependencies dynamically

Like
Replying to

That is something not possible with this example , you can define dynamic field dependencies through custom settings , custom metadata or Custom Objects.


You can strong the Controlling Field and Dependent field and values as a Long Text with comma separated or Saving values as a child records. This is one of the way where you can able to develop such complex behaviour

Like
bottom of page