Fieldset with Apex code

Fieldset apex code salesforce

A field set is a grouping of fields for same object. We can use dynamic bindings to display field sets on our Visualforce pages. Fieldset is very useful when we are working with managed package.
If we are using standard controller, then using fieldset in visualforce is straight forward. You can view my previous fieldset with visualforce page for using fieldset in visualforce pages.
But if we are using custom controller or extension, then we may need to query fieldset fields in SOQL query. So we will use dynamic SOQL query for querying all fields of fieldset.
By using dynamic SOQL query in Apex and using fielset in visualforce and Apex code. Our code will become dynamic, then we can add, remover or reorder fields in fieldset. By doing so, our code will become dynamic. There is no need to modify code when we will do any change in fieldset.
In the example below, we will use fieldset to display account list on visualforce page. We will use dynamic SOQL query in Apex code.
First we need to create a fieldset. Go to Setup > Customize > Accounts > Field Set
Click on new. Enter all mandatory fields. Also drag and drop all required fields in fieldset.

Visualforce Page
<apex:page controller="fieldsetcontroller" >
  <Apex:form >
     <apex:pageBlock >

          <apex:pageBlockSection title="Account" collapsible="false">
             <apex:pageBlockTable value="{!accList}" var="acc">
                 <apex:repeat value="{!$ObjectType.Account.fieldsets.AccountField}" var="fieldValue">
                     <apex:column value="{!acc[fieldValue]}">
                     </apex:column>
                 </apex:repeat>
             </apex:pageBlockTable>
          </apex:pageBlockSection>

          <apex:pageBlockSection title="Account Dynamic query" collapsible="false">
              <apex:outputText value="Query is: {!queryString}" />
          </apex:pageBlockSection>
      </apex:pageBlock>
     </apex:form>    
</apex:page>

Apex class
public class fieldsetcontroller 
{
    public String queryString{get;set;}
    public List<Account> accList{get;set;}
    public fieldsetcontroller ()
    {
        queryString = 'select id';
        for(Schema.FieldSetMember fld :SObjectType.Account.FieldSets.AccountField.getFields()) {
         queryString += ', ' + fld.getFieldPath();
        }
        System.debug('@@queryString-->'+queryString);
        queryString += ' from Account limit 5';
         
        acclist = Database.query(queryString);
    }
}
We will get following output in visualforce page:

0 comments:

Post a Comment