5

Background

I have a Map of sObjects and a List of API field names (from Custom Settings) to dynamically control the fields that display in a table on a Visualforce page.

Here's the Apex to get all fields:

// get all fields from Custom Settings
Map<String, Field__c> Fields = Field__c.getAll(); 
List<String> Columns = new List<String>();
for(Field__c f : Fields.values()) { Columns.add(f.API_Name__c); }

A custom extension for a Visualforce page is used to retrieve the fields and an <apex:repeat> iterates over them. It looks something like this (I changed the code to be more generic, for this example):

<table class="datatable display" border="0" cellpadding="0" cellspacing="0">
  <thead>
    <!-- ... -->
  </thead>
  <tbody>
    <apex:repeat value="{!sObjectMap}" var="key">
      <tr id="{!sObjectMap[key]['Id']}">
        <apex:repeat value="{!Columns}" var="col">
          <td>
            <apex:outputpanel rendered="{!IF(OR(col=='Name',col=='Subject'),true,false)}">
              <apex:outputlink value="/{!sObjectMap[key].Id}" target="_blank">
                <apex:outputfield value="{!sObjectMap[key][col]}" />
              </apex:outputlink>
            </apex:outputpanel>
            <apex:outputpanel rendered="{!IF(OR(col=='Name',col=='Subject'),false,true)}">
              <apex:inputfield value="{!sObjectMap[key][col]}" showDatePicker="false" />
            </apex:outputpanel>
          </td>
        </apex:repeat>
      </tr>
    </apex:repeat>
  <tbody>
<table>

Question

How can I get the type of the <apex:inputfield> that is being displayed when it is dynamically determined (either in an <apex:repeat>, <apex:pageblocktable>, or <apex:datatable>)? Ideally this type should be stored somewhere on the field so that it can be selected using jQuery.

7

I think I found a solution using the $ObjectType global variable.

<apex:inputfield value="{!sObjectMap[key][col]}" 
    styleClass="type-{!$ObjectType.Custom_sObject__c.Fields[col].type}" />

This results in the type being added as a CSS class.

Here's how a picklist renders:

<select id="j_id0:j_id8:j_id15:0:j_id17:4:j_id23" 
    class="type-picklist" name="j_id0:j_id8:j_id15:0:j_id17:4:j_id23">

And here's a date field:

<input id="j_id0:j_id8:j_id15:0:j_id17:5:j_id23" class="type-date" type="text" 
    value="10/2/2013" size="12" name="j_id0:j_id8:j_id15:0:j_id17:5:j_id23">

This way, I can use jQuery to select all picklist fields simply by selecting all inputs with the type-picklist class (or dates with the type-date class).

var allPicklistInputs = $(".type-picklist");
var allDateInputs = $(".type-date");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.