[SalesForce] Dynamically create filters based on object fields

In my visualforce page I am showing various fields from Account page where user can input values and search for matching accounts.
Is it possible to create these filters dynamically, may be using describe sobject query. So that all fields come automatically on vf page

Best Answer

Depending on what you want to do, there are a couple of solutions.

If you want to display all Account fields I would suggest using getDescribe().fields.getMap().keySet() and then iterating over the result in an apex:repeat to build you page.

public with sharing class SearchPageController
{
    public final Account anAccount { get; set; }
    public List<String> searchFields { get; private set; }


    public SearchPageController()
    {
        anAccount = new Account();
        searchFields = new List<String>(Account.getSObjectType().getDescribe().fields.getMap().keySet());
    }
}

Then on your page (you'll want to adjust the 'look and feel', as this example doesn't look great!):

<apex:page controller="SearchPageController">
    <apex:form>
        <apex:repeat value="{!searchFields}" var="field">
            <apex:outputText value="{!field}"/>
            <apex:inputField value="{!anAccount[field]}"/>
            <br/>
        </apex:repeat>
    </apex:form>
</apex:page>

You can then use the values stored within the Account object inside your controller to build your dynamic SOQL query for your search.


If you only want to display some of the fields on Account then I would suggest using Field Sets, in which case you need to change your controller to something like the following:

public with sharing class SearchPageController
{
    public final Account anAccount { get; set; }
    public List<String> searchFields { get; private set; }


    public SearchPageController()
    {
        anAccount = new Account();
        searchFields = new List<String>();

        for(Schema.FieldSetMember f : SObjectType.Account.FieldSets.YourFieldSet.getFields()) 
        {
            searchFields.add(f.getFieldPath());
        }
    }
}

OR, you can change your apex:repeat to use the Field Set directly.

<apex:page controller="SearchPageController">
    <apex:form>
        <apex:repeat value="{!$ObjectType.Account.FieldSets.YourFieldSet}" var="field">
            <apex:outputText value="{!field.Label}"/>
            <apex:inputField value="{!anAccount[field]}"/>
            <br/>
        </apex:repeat>
    </apex:form>
</apex:page>

Again, you can then use the values stored within the Account object inside your controller to build your dynamic SOQL query (or whatever you're using) for your search.

Related Topic