Use a Fieldset in APEX and Visualforce

There are times where you may need to access fieldsets in APEX to dynamically generate pages in Visualforce.  In Apex, there are 2 main ways to do this, and you can select which approach you need based on what data you have available at runtime.

Getting Fieldsets in Visualforce

You can access fieldsets directly from a Visualforce page using this type of approach:

 

<apex:repeat value="{!$ObjectType.Contact.FieldSets.properNames}" var="f">
     <apex:outputField value="{!Contact[f]}" />
</apex:repeat>

Getting Fieldsets in Apex Code

Scenario 1: You know the sObject and the specific name of the fieldset you need.

In this scenario, you’re just trying to show specific fieldset(s) on a page, and there is no need to dynamically fetch fieldsets based on any conditions.  To do this use the following:

 

public List<Schema.FieldSetMember> getFields() {
     return SObjectType.Contact.FieldSets.properNames.getFields();
}

You can then access the getFields list in a Visualforce page like this:

 

<apex:repeat value="{!getFields}" var="g">
     <apex:outputField value="{!Contact[g]}" />
</apex:repeat>

Scenario 2: You need to dynamically fetch specific fieldsets based on some conditions, perhaps a Custom Setting that dictates what fieldsets apply to a specific page or record type.

The following uses no concrete sObject calls in order to fetch a fieldset.  You can use this if you’re dynamcially grabbing the sObject and Fieldset in a query first, and then grabbing the specific fieldset(s) to use.

 

public static List<Schema.FieldSetMember> getFieldSet(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();
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s