Saturday, 24 November 2012

Accessing Fieldsets from Controller

Here i am trying to explain ,how to get field set in controller and how to get field values from a particular fieldset and display those fields in fieldset on visualforce page.

I am taking Account object for explainin this.

To get all the field sets in Account object
Schema.SObjectType.Account.fieldSets.getMap().keySet();

the above line gives you the set of field sets in Account object

Now to get the fields from a particular field set associated with Account object we need to write as shown below

Schema.SObjectType.Account.fieldSets.getMap().get('balu131__account_fieldset').getFields()

here "balu131__account_fieldset" is the name of the Field set of Account.

the above line gives you the different properties of fields in that field set like getLabel,getfieldpath,getType etc.,
to get field name we need to use "getFieldPath" property.
the following snippet shows you how to hold the field names.
List<string> fieldnames=new List<string>();//this is a list preparing for holding the field names.

for(Schema.FieldSetMember  s:Schema.SObjectType.Account.fieldSets.getMap().get('balu131__account_fieldset').getFields()){
fieldnames.add(s.getFieldPath()); //adding field names to list
}

Eg: Accessing field set in controller and displaying that on visualforce page
====
Controller
=======

public with sharing class Fieldsetclass1 {
public List<string> fieldnames{get;set;}
public Account actobj{get;set;}
public Fieldsetclass1(){
actobj=new Account();
fieldnames=new List<String>();
for(Schema.FieldSetMember s:Schema.SObjectType.Account.fieldSets.getMap().get('balu131__account_fieldset').getFields()){
fieldnames.add(s.getFieldPath());

}
}
public pagereference save(){
insert actobj;
return new pagereference('/'+actobj.id);
}

}



Page
====

<apex:page controller="Fieldsetclass1" sidebar="false">
<apex:form >
<apex:pageBlock >
<apex:pageBlockButtons >
<apex:Commandbutton value="Save" action="{!save}" rerender="pbt"/>
</apex:pageBlockButtons>
<apex:pageBlockSection >
<apex:repeat value="{!fieldnames}" var="fname">
<apex:inputField value="{!actobj[fname]}"/>
</apex:repeat>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Output:
=====




No comments:

Post a Comment