Salesforce Field Sets – a limitation and a workaround
By Vincent on April 24, 2011
Field sets make so much sense, and I was really looking forward to being able to set up some very easy to maintain code. Unfortunately field sets do have one limitation that I recently ran into. You can’t access them from Apex Code.
To be fair, before Field Sets, you really had no options of displaying a dynamic set of fields on a Visualforce page. Field sets give you some great flexibility which wasn’t there before, so Field Sets should certinly be a part of all your future Visualforce dev design. I only wish it was a one stop shop for my field definitions for both my Visualforce pages and their supporting Apex code.
An example a typical scenario where Field Sets come in handy, is the following. Let’s say you’re creating a Visualforce page that displays some results from an Apex query. In order to change the fields that are shown on the page, or even the order of the fields, you had to get your developer to change both the Visualforce page and/or the Apex query that goes along with it.
So with Field Sets, the fields that are shown on the Visualforce page can now be dynamically configured by a Salesforce Administrator. But what about the Apex query code? From Apex, we can’t access the field set, so we can’t directly know what fields the Visualforce page is now expecting. Is there anyway that we can return the correct fields for the objects that will be displayed by the Field Set?
Yes, there is. The Apex side of the equation already has a load of options for storing configuration data. One approach is to store the field list data in a Custom Setting. The fields that you list should correspond to the field used in the Field Set. The only downside of this approach is the double maintainence that needs to occur. Now when you modify the field set, you also have to remember to change the Custom Setting data too.
So until you can access Field Sets from Apex code, this workaround should allow your Aministrators to add and remove fields from those custom Visualforce pages without having to get developers involved.