LaceySnr.com - Salesforce Development Posts by Matt Lacey

Field Sets and Custom Styles - Saving Time And Adding Value

Posted: 2011-03-03

Last week I needed to work on a Visualforce Page which dumped a bunch of contact and related account data on screen, and one of our guys suggested it might be a good place to try out the new field sets (part of the latest release), though things do get a little complex when you want to leverage custom styling at the same time.

About Field Sets

Field sets allow for end-user customisation of your custom pages, you tell the page to render the field set, the user can control which fields are in the set – they're simple, effective and save a helluva lot of development time whilst providing a more flexible solution; everybody wins. The Salesforce blog has an example of how to use sets , I won't duplicate what they say here but they do assume that you'll be inserting the fields in a regularly styled Visualforce page using the classic rendering hierarchy, namely: <apex:pageBlock>, <apex:pageBlockSection>, <apex:pageBlockSectionItem>.

Custom Look and Feel

We needed to customise our page quite heavily and as such I needed to be able to get the labels for the fields separately to the field values, and I found you could do this using the field array attached to each object (e.g. {!$ObjectType.Account.Fields[f].label}). The following code loops over the Product Interest field set which has been defined on Account, rendering the label and an input or output field (depending on a public controller member variable) in a standard HTML table.

<apex:repeat value="{!$ObjectType.Account.FieldSets.Product_Interest}" var="f">
  <tr>
    <td class="left">
      <apex:outputText styleClass="bold" value="{!$ObjectType.Account.Fields[f].label}"/>
    </td>
    <td class="right">
      <apex:inputField styleClass="vfInputField" value="{!Contact.Account[f]}" rendered="{!NOT(bReadOnly)}"/>
      <apex:outputField styleClass="vfInputField" value="{!Contact.Account[f]}" rendered="{!bReadOnly}"/>
    </td>
  </tr>
</apex:repeat>

Easy to code, easy to configure and ultimately more flexible – this is what the force.com platform does best!