How to get FieldSet fields in Apex Dynamically (fieldset name is not static)

String fieldSetName = 'Account_FieldSet';
String ObjectName = 'Account';

I wanted get list of all fields from this fieldset.

I know if fieldset name is hardcoded in the apex then following syntax works –

SObjectType.Account.FieldSets.Account_FieldSet.getFields();

But here main issue is Object name and fieldset name will come at runtime.

Answer

How to get FieldSet fields in Apex Dynamically (fieldset name is not static)

Here is the method I came up with lots of trial and errors –

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();

    //system.debug('====>' + DescribeSObjectResultObj.FieldSets.getMap().get(fieldSetName));

    Schema.FieldSet fieldSetObj = DescribeSObjectResultObj.FieldSets.getMap().get(fieldSetName);

    //List<Schema.FieldSetMember> fieldSetMemberList =  fieldSetObj.getFields();
    //system.debug('fieldSetMemberList ====>' + fieldSetMemberList);  
    return fieldSetObj.getFields(); 
}  

You can use result as follows –

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
}

Attribution
Source : Link , Question Author : Prafulla Patil , Answer Author : Prafulla Patil

Leave a Comment