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, let's try using dynamic bindings in VisualForce 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 Page “fieldSetAsCSV.page”: This page generates a CSV of field names in the field set. This page accepts two request parameters, i.e.
sobjectName: Sobject API Name, whose field set needs to be loaded.
fieldSetName: The name of the field set to be loaded.
2. Apex Utility Class “FieldSets”: This class calls the above VF page and returns 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!
The Summer ’12 release is getting this feature natively in the Apex describe information. So the above code is no more required. Here is the snippet from the Summer’12 release docs:
Thanks to Daniel Hoechst for this update!
Your thoughts
Looking forward to the same!