Visualforce dynamic binding works for table columns

I was pleasantly surprised this week to find out that some customization that I needed to implement – allowing the set of columns in an apex:pageBlockTable to be specified in a custom setting – could be implemented in Visualforce using the most obvious solution:

<apex:pageBlockTable var="c" value="{!contacts}">
    <apex:repeat var="f" value="{!fields}">
        <apex:column value="{!c[f]}"/>
    </apex:repeat>
</apex:pageBlockTable>

where “contacts” is a list of Contact objects and “fields” is a list of Contact field names obtained from a custom setting holding comma separated values. (The query that populates “contacts” must also use the field names to avoid the “SObject row was retrieved via SOQL without querying the requested field” error.)

Advertisements

3 thoughts on “Visualforce dynamic binding works for table columns

  1. Sure. Here is a simple example:

    public class TestController {
    
        // This value could come from a custom setting
        private static String FIELDS_CSV = 'FirstName, LastName, Birthdate';
    
        public Contact[] contacts {
            get {
                // Specify where clause as needed
                return Database.query('select ' + FIELDS_CSV + ' from Contact where LastName = \'Doe\'');
            }
        }
        
        public String[] fields {
            get {
                return parseCsv(FIELDS_CSV);
            }
        }
        
        private String[] parseCsv(String s) {
            List<String> l = new List<String>();
            for (String f : s.split(',')) {
                l.add(f.trim());
            }
            return l;
        }
    }
    

    with the matching page:

    <apex:page controller="TestController">
        <apex:pageBlock>
            <apex:pageBlockTable var="c" value="{!contacts}">
                <apex:repeat var="f" value="{!fields}">
                    <apex:column value="{!c[f]}"/>
                </apex:repeat>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:page>
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s