Tuesday, May 31, 2011

Dynamic Binding Salesforce

Visualforce Dynamic Binding lets you write generic Visualforce pages to display information about records without necessarily knowing which fields to show. By determining the fields to show at runtime rather than compile time, Visualforce Dynamic Bindings allows for the presentation of data specific to each subscriber with very little coding. Developers working with managed packages will find this feature especially useful.

In the below example I have created a class and fetching all the fields of account object in that class.

public class DynamicBinding
    public Account account{get;set;}
    // constructor
    public DynamicBinding(){
        account = new Account();
    // get sobject fields of account object
    public static List<String> getSobjectFields() 
            List<String> fields = new List<String>();
            Map<String,Schema.SObjectType> gd = Schema.getGlobalDescribe();
            Schema.SObjectType sobjType = gd.get('account');
            Schema.DescribeSObjectResult r = sobjType.getDescribe();
            Map<String,Schema.SObjectField> M = r.fields.getMap();
            for(String fieldName : M.keyset())
                    Schema.SObjectField field = M.get(fieldName);                                                    
                    Schema.DescribeFieldResult fieldDesc = field.getDescribe();
            return fields;

I have created a vf page and set it controller to "DynamicBinding" class.I am using the account object and "SobjectFields" property to create the page dynamically.

<apex:page controller="DynamicBinding">
  <apex:form >
              <apex:repeat value="{!SobjectFields}" var="fieldName">
                   <apex:inputField value="{!account[fieldName]}"/>


  1. except that r.fields does NOT return lookup fields

  2. r.fields.getMap() returns all the fields (including lookups) of an object.

  3. hi dev,
    using same code is it possible getting the custom object fields dynamically, i can try but it is throw some errors

    if it is possible help me