Monday 26 October 2015

Visualforce Field Sets

Here at BrightGen, we've always tended to advise customers that replacing edit pages with Visualforce should be a last resort, as it means coding is required if additional fields are created on the sobject.  With the advent of Field Sets in Spring 11, this becomes much less of an issue.

Field sets are well documented in the Salesforce help, so I won't reproduce any of that here.  Instead, here's an example using field sets to create an edit page with additional Visualforce functionality.

Firstly, I've created two Field Sets on the Account standard object.  The first is for general fields that I'll show at the top of the record:


While the second is for Address-specific fields:


Next I create my Visualforce page. The key markup is as follows:





















<apex:pageBlock mode="maindetail" title="Account Edit">
        <apex:pageBlockButtons >
           <apex:commandButton value="Cancel" action="{!cancel}"/>
           <apex:commandButton value="Save" action="{!save}"/>
        </apex:pageBlockButtons>
        <apex:pageBlockSection title="General">
           <apex:repeat value="{!$ObjectType.Account.FieldSets.General}" 
                    var="field">
              <apex:inputField value="{!Account[field]}" />
           </apex:repeat>
        </apex:pageBlockSection>
        <apex:pageBlockSection title="Address">
           <apex:repeat value="{!$ObjectType.Account.FieldSets.Address}" 
                    var="field">
              <apex:inputField value="{!Account[field]}" />
           </apex:repeat>
        </apex:pageBlockSection>
        <apex:pageBlockSection title="Bar Chart">
    <div id="barchart" style="width: 450px; height: 25px;"></div>
 </apex:pageBlockSection>
     </apex:pageBlock>

Using the field set is as simple as accessing it from the $ObjectType global variable and iterating the fields:






<apex:repeat value="{!$ObjectType.Account.FieldSets.Address}" 
           var="field">
      <apex:inputField value="{!Account[field]}" />
   </apex:repeat>

The additional Visualforce functionality is a simple Dojo barchart, which is drawn in by Javascript into the barchart div.

Here's the generated page:


As an Administrator, if I then decide that I'd like to add the Industry field to the page.  I simply edit my General Field Set to add the field to the end of the set, refresh the page, and the new field is present with zero coding effort:


I've already used this in one solution that combines record creation with embedded searching capabilities.

No comments:

Post a Comment