Have you ever wanted a page or form to dynamically refactor itself based off of user selections? Record types on page layouts are useful, but there are instances where you might want to conditionally hide or show fields based off of selections on the page. Thankfully this is possible using a few standard Visualforce components and a standard controller!

Displaying Visualforce Fields or Sections Dependent on Data

In order to create this functionality, you will need to add three main elements to your form:

    1. <apex:actionRegion>: You will need to add an action region within your form around the controlling field components. This will distinguish what region of the form should be processed by Force.com when an AJAX request is generated.
    2. <apex:actionSupport>: This component controls the behavior of the form and adds AJAX support to your actionRegion. If you add this component directly below a field, you can associate DOM events to that field to generate an AJAX request. This component only provides support for invoking custom or standard controller action methods from other Visualforce components, but if you would like to invoke controller methods in JavaScript you can use actionFunction.
    3. <apex:__?__ … rendered=”{!MyObject.Field == ‘field value’}” … >: Add conditional logic within the rendered attribute to the component(s) you want to conditionally show.
The sample below shows a simple ‘New Case’ edit page, where a section with a few custom fields will render if the case type ‘Electronic’ is selected in the form. Because we are using the AJAX components above, this will happen dynamically on change of the case type picklist value.

Create Your Own Conditional Custom Visualforce Page

Now that you’ve seen this example, you can see how simple it can be to add conditional logic to make dynamic custom layouts. If you are unfamiliar with building custom pages on Force.com, you can find a similar example here with more context into how each element the MVC model comes into play.

Get the latest Salesforce Developer blog posts and podcast episodes via Slack or RSS.

Add to Slack Subscribe to RSS