Using FieldSet with Visualforce and Apex

Using FieldSet with Visualforce and Apex

One of the disadvantages comes up with Custom Page or Overriding New or Edit button with Visualforce page is its “Maintenance”, if New Filed is Added or needed to remove field we have to modify our code every time.

A fieldset is a grouping of fields for the same object. We can use dynamic bindings to display fieldsets on our Visualforce pages. Fieldset is very useful when we are working with a managed package.

By using dynamic SOQL query in Apex and using fielset in Visualforce and Apex code we can create effective Visualforce pages with the ability to change Fields and its Sequence any time without modifying any code. Isn’t that great.

Let’s start with using Field set in Salesforce.

In the example below, we will use fieldset to display the account list on the visualforce page. We will use a dynamic SOQL query in the Apex code.

First, we need to create a fieldset. Go to Setup > Customize > Accounts > Field Set
Click on new and name the fieldset as “accountFieldSet”. Enter all mandatory fields. Also, drag and drop all required fields in the fieldset.

Visualforce Page:

<apex:page controller="AccountFieldSetController" tabStyle="Account">
  <apex:form >
      <apex:pageblock >        
          <apex:pageBlockSection title="Account list" collapsible="false">
             <apex:pageBlockTable value="{!accountList}" var="acc">
                 <apex:repeat value="{!$ObjectType.Account.fieldsets.accountFieldSet}" var="fieldValue">
                     <apex:column value="{!acc[fieldValue]}">
                     </apex:column>
                 </apex:repeat>
             </apex:pageBlockTable>
          </apex:pageBlockSection>
           
          <apex:pageBlockSection title="Account Dynamic query" collapsible="false">
              <apex:outputText value="Query is: {!queryString}" />
          </apex:pageBlockSection>
           
      </apex:pageblock>
    </apex:form>
</apex:page>

Apex Code:

public class AccountFieldSetController {
    public String queryString{get;set;}
    public List<Account> accountList{get;set;}
    public AccountFieldSetController(){
        queryString = 'select id';
        for(Schema.FieldSetMember fld :SObjectType.Account.FieldSets.accountFieldSet.getFields()) {
         queryString += ', ' + fld.getFieldPath();
        }
        queryString += ' from Account limit 5';
         
        accountList= Database.query(queryString);
    }
     
}

We will get following output in visualforce page:

Great We have Done it

I hope, this article will help you in understanding the field sets more deeper and solved your problem.

You can read Apex Documentation regarding FieldSet here