April 20, 2012

Accessing Sobject Field Sets in Apex Code !

I recently came across a problem, where I need to query the fields to be shown via FieldSet via Apex Code (No Standard Controller Love). After struggling for a while with Apex docs, I googled for the same and found an idea posted for the same.

So, I thought lets try using dynamic bindings in visual force if they can get the job done for me. Fortunately it worked like a charm in one go. Here is the solution

Code

The code is comprised of

  1. Visualforce PagefieldSetAsCSV.page” : This page generates a CSV of field names in the field-set. This page accepts two request params i.e.
    • sobjectName :  Sobject API Name, whose field set needs to be loaded.
    • fieldSetName : The name of field set to be loaded.
  2. Apex Utility Class “FieldSets” :  This class calls the above VF page and returns back a collection of fields for the given fieldset and sobject.

Visualforce Page

<apex:page contentType="application/CSV" showHeader="false" sidebar="false" >
<apex:repeat value="{!$ObjectType[$CurrentPage.parameters.sobjectName].fieldsets[$CurrentPage.parameters.fieldSetName]}" var="fld">{!fld},</apex:repeat>
</apex:page>

 

Apex Utility Class

public class FieldSets {
    /**
        Returns a list of field api names for the given sobject and fieldset name
    */
    public static String[] load(String sobjectName, String fieldSetName){
        PageReference pr = Page.fieldSetAsCSV;
        pr.getParameters().put('sobjectName', sobjectName);
        pr.getParameters().put('fieldSetName', fieldSetName);
        String csv = pr.getContent().toString();
        return csv.split(',');
    }
}

 

Testing the fixture

Assuming there is a field set named “DemoFieldSet” on Account, here is the sample code to use the above fixture in Apex

String[] fieldNames = FieldSets.load('Account', 'DemoFieldSet');

for (String fldName : fieldNames) {
 System.debug(fldName);   
}

 

Summer’12 Update !

Summer’12 release is getting this feature natively in Apex describe information.  So the above code is no more required. Here is the snippet from Summer’12 release docs:

image

Thanks to Daniel Hoechst for this update !

Your thoughts

Looking forward for the same !