Monday, June 4, 2012

Apex Describe support for Fieldsets

Visualforce dynamic bindings have supported field sets for some time. In Summer ’12, Apex provides describe support for field sets, which makes it possible to dynamically generate the SOQL necessary to load all fields in a field set. This makes field sets easier to use in Visualforce pages that use custom controllers.

This sample uses Schema.FieldSet and Schema.FieldSetMember methods to dynamically get all the fields in the ContactInfo field set for the Contact object. The list of fields is then used to construct a SOQL query that ensures those fields are available for display. The Visualforce page uses this class as its controller.

public class ContactDetails{
    public Contact con { get; set; }
    public ContactDetails() {
        this.con = getContactDetails();
    }
    public List getFields() {
        return SObjectType.Contact.FieldSets.ContactInfo.getFields();
    }
    private Contact getContactDetails() {
        String query = 'SELECT ';
        for(Schema.FieldSetMember f : this.getFields()) {
            query += f.getFieldPath() + ', ';
        }
        query += 'Id, Name FROM Contact LIMIT 1';
        return Database.query(query);
    }
}
The Visualforce page using the above controller is simple:

   
       
           
               
           
           
               
                   
               
           
      
   


1 comment: