Using fieldset in a Visualforce page

Suppose you want to display some fields in a page and you wish to keep the flexibility to change which fields are displayed. In such a scenario you could use field sets to add or remove the fields you desire.Which ever fields are included in the field set will be displayed in page. For this you will need to create a field set on whichever object you wish, then you can access it directly in vf page.

As an example say, you want to display output fields on a vf page from account. Firstly, you create a fieldset say named "AccontractField_Set". Then you can use repeat attribute to iterate through all the fields as shown in below example:

Visual force page displaying account fields picked up from field set "AccontractField_Set"

<apex:page standardController="Account">
  <apex:form >
      <apex:pageblock >
             <apex:repeat value="{!$ObjectType.Account.fieldsets.AccontractField_Set}" var="fieldVal">
                    <apex:Inputfield value="{!Account[fieldVal]}"/>
             </apex:repeat>
        </apex:pageblock>
    </apex:form>
</apex:page> 


In this statement "<apex:repeat value="{!$ObjectType.Account.fieldsets.AccontractField_Set}" var="fieldVal">",  'Account' is the object from where you are picking the field set. You can change this object name and the field set name accordingly as per your requirement.

5 comments:

  1. When I tried to prepopulate fields in a fieldset and displaying it in visualforce page using ...it is not working. Any help?

    ReplyDelete
  2. If it is directly from the field set as explained above then you should'nt have any problem displaying it, as it is pretty staright forward. Make sure you have put the correct field set api name and have followed the correct syntex as explained in the above example.

    ReplyDelete
  3. I have copied same code and than save the page it gives error like as below...
    Error: Unknown property 'Account.fieldsets.AccontractField_Set'

    ReplyDelete
  4. I have copied same code and than save the page it gives error like as below...
    Unknown property 'Account.fieldsets.AccontractField_Set'
    Unknown property 'ApexPagesDescribeSObjectResult.fieldset'

    ReplyDelete
    Replies
    1. May be you created field set on contact but, trying to fetch the field set from account and so the unknown property issue.

      Delete