Get FieldSet label on VisualForce page via apex for custom object

apexcustom-objectfieldsetslabelvisualforce

I am creating a VisualForce (VF) page as PDF as report for a custom object MyCustomObject supporting different languages. Therefore I want to retrieve the label of a FieldSet, to dynamically account for different languages depending on user settings.

I found Access label of Field Set in Visualforce which doesn't seem to work for custom objects.

Fieldset MyFieldSet

I created a fieldset for my MyCustomObject object, added a few fields and translated the FieldSetLabel to different languages.

label=MyFieldSetLabel
ApiName=MyFieldSetApiName
Fields=[...]

VF page – hardcoded fieldset label

This example uses a hard coded title for a block section header, not accounting for langugage differences

<apex:pageBlockSection title="HARDCODED TITLE">
    <apex:repeat value="{!$ObjectType.MyCustomObject__c.fieldsets.MyFieldSet}"
       ....
    </apex:repeat>
</apex:pageBlockSection>

VF page – dynamic fieldset label

Aim is a dynamic section tatle based on FieldSetLabel, accounting for translations.

<apex:pageBlockSection title="{!$ObjectType.MyCustomObject__c.fieldsets.MyFieldSet.Label}">
    <apex:repeat value="{!$ObjectType.Account.fieldsets.MyFieldSet}"
       ....
    </apex:repeat>
</apex:pageBlockSection>

Since I am able to create translations for my FieldSetLabel it must be possible to dynamically access it. When creating VF pages with multi-langugage support, you cannot rely on a hard-coded fieldset title.

Any idea how to retrieve a FieldSet label via apex on a VisualForce page?

Best Answer

You can retrieve it dynamically using DescribeSObjectResult like below.

In Apex controller:

public String getFieldSetLabel() {

    String objectName = 'Your object API Name';
    String fieldSetName = 'Your fieldset API Name';
    Schema.SObjectType objectType = Schema.getGlobalDescribe().get(objectName);
    Schema.DescribeSObjectResult objectDescribe = objectType.getDescribe();
    Map<String, Schema.FieldSet> fieldSetMap = objectDescribe.fieldSets.getMap();
    Schema.FieldSet fieldSet = fieldSetMap.get(fieldSetName);
    String fieldSetLabel = fieldSet.getLabel();
    return fieldSetLabel;
}

In Visualforce page:

<apex:pageBlockSection title="{!fieldSetLabel}">