Search This Blog

Friday, April 24, 2015

Field Set in Salesforce

A field set is a grouping of fields.You can dynamically display group of fields in visualforce page.
For example, you could have a field set that contains fields describing a user's first name, middle name, last name, and business title.
If the page is added to a managed package, administrators can add, remove, or reorder fields in a field set to modify the fields presented on the Visualforce page without modifying any code.

steps:
1) Create a Field Set(for example in account object)


Go to Setup --> Customize --> Accounts --> Field Sets --> Click on "New" button.

Enter values and click save.
Now Go to Setup --> Customize --> Accounts --> Field Sets -->click on "Edit" of created fieldset.

Drag and drop the fields as you like into "Avalable for the field set" and "in the field Set"
as shown in the image  below.


then save the alyout.
2)Create apex class as shown below.

public class DisplayAccount{

    public Account acc { get; set; }
    
    public DisplayAccount() {
        this.acc= getAccounts();
    }

    public List<Schema.FieldSetMember> getFields() {
        return SObjectType.Account.FieldSets.DisplayAccount.getFields();
    }

    private Account getAccounts() {
        String query = 'SELECT ';
        for(Schema.FieldSetMember f : this.getFields()) {
            query += f.getFieldPath() + ', ';
        }
        query += 'Id, Name FROM Account LIMIT 1';
        return Database.query(query);
    }
}

3)create visualforce page as shown below.
<apex:page controller="DisplayAccount">
    <apex:form >

      <apex:pageBlock title="Account Details">
          <apex:pageBlockSection title="Product">
              <apex:inputField value="{!acc.Name}"/>
          </apex:pageBlockSection>
      
          <apex:pageBlockSection title="DisplayAccount">
              <apex:repeat value="{!fields}" var="f">
                  <apex:inputField value="{!acc[f.fieldPath]}" 
                      required="{!OR(f.required, f.dbrequired)}"/>
              </apex:repeat>
          </apex:pageBlockSection>
  
        </apex:pageBlock>

    </apex:form>  
</apex:page>

4) Run the vf page.The output will be as below.
Enjoy Coding..