display fields based on selection on a picklist selection

Prady picture Prady · Apr 4, 2012 · Viewed 19.6k times · Source

I have a VF page where i am using a apex:pageblocktable to display bunch of records. One of the columns is a picklist and i need to display/not display fields according to selection on the picklist.

 <apex:pageBlockTable value="{!showRecord}" var="item">
  <apex:column headerValue="Delivery">
    <apex:inputField value="{!item.delivery__c}"/>
  </apex:column>
  <apex:column headerValue="Roadway">
    <apex:inputField value="{!item.road__c}"/>
  </apex:column>
  <apex:column headerValue="Rail">
    <apex:inputField value="{!item.rail__c}"/>
  </apex:column>
 </apex:pageBlockTable>

in the above code delivery_c is picklist with values roadways and railways. if the user selects roadways then i need to display road--c and if user selects railways then i need to display rail_c

How can i go about doing that?

Thanks

Answer

Kevin O&#39;Hara picture Kevin O'Hara · Apr 5, 2012

One way to do this would be to use partial-page refreshes in Visualforce.

Put both fields in the same column and use the "rendered" attribute to dynamically show/hide the field using an if-statement. Then you set up an AJAX onchange event handler for the delivery__c field using the actionSupport tag. This will basically listen for that field to change then refresh the table on the page. Each time this is refreshed, your if statements will be re-evaluated and result in showing one of the two fields in that column.

I didn't get a chance to try this but I think it should work.

<apex:pageBlockTable id="mytable" value="{!showRecord}" var="item">
  <apex:column headerValue="Delivery">
    <apex:actionRegion>        
      <apex:inputField value="{!item.delivery__c}">
        <apex:actionSupport event="onchange" reRender="mytable">
      </apex:inputField>
    </apex:actionRegion>
  </apex:column>
  <apex:column headerValue="Delivery Type">
    <apex:inputField rendered="{!item.delivery__c='Road'}" value="{!item.road__c}"/>
    <apex:inputField rendered="{!item.delivery__c='Rail'}" value="{!item.rail__c}"/>
  </apex:column>
</apex:pageBlockTable>