anusha(salesforce developer)

Thursday 21 July 2016

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

No comments:

Post a Comment