Tuesday, December 20, 2016

Visualforce - Beyond Basics Series 30 - Use FieldSets for FutureProof

What is FieldSet ?

It is nothing but grouping the related fields in the sObject & giving them a Name.


What is the use of it ?

Since, it's a group of fields it can be used as a collection, rather than individual fields. At beginning, it may seems not required, but as organization grows, this feature is very important to maintain the Org health.


Where should be used ?

This will be used mainly in Visualforce & Apex. For example, you have created a feature which requires 100 fields to be processed by the user. Would you be happy to add inputField/outputField in the Visualforce page for all 100 fields ?  Won't you think is there any better way ?
yes, fieldset is the solution. you just fieldset to iterate through the fields & use them. These are the usefulness,

  1.   efficient coding
  2.   less maintainance
  3.   future proof - you can add a field or remove from the fieldset, but doesn't need to change the page.


How to use it ?

In visualforce page, you normally use repeat component to iterate through them & then, either input/output the values according the requirements.


Where is the Code ?

I have illustrated how to use a fieldset to iterate & display the values in the page. you need to create the fieldset before running the page.

<apex:page standardController="Opportunity">
<apex:pageBlock>
<apex:pageBlockSection>
<!-- Iterating through fieldset -->
<apex:repeat value="{!$ObjectType.Opportunity.FieldSets.OppFieldSet}"
var="field">
<apex:pageBlockSectionItem>
<!-- Label -->
<apex:outputPanel layout="none">
<!-- Field Label -->
<apex:outputLabel value="{!$ObjectType.Opportunity.fields[field].Label}"
rendered="{!NOT(CONTAINS(field, '.'))}"/>
<!-- Parent Field Label -->
<apex:outputLabel value="{!field}" rendered="{!CONTAINS(field, '.')}"/>
</apex:outputPanel>
<!-- Field value -->
<apex:outputField value="{!Opportunity[field]}"/>
</apex:pageBlockSectionItem>
</apex:repeat>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>
view raw gistfile1.txt hosted with ❤ by GitHub

1 comment:

Thanks for reading my blog !