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.

  • 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
    }
    

    This was marked as community wiki (I just discovered it while looking for a way to do field sets dynamically), not sure if that was intentional but I've removed it because you deserve the rep for it!

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used