[SalesForce] Rerendering conditionally required fields in VF – how to make field ‘unrequired’ upon rerender

My scenario:

  • I have two fields, each of which is tied to third field's picklist values.
  • Only one of those two fields should display, depending on the selected picklist value.
  • Whichever of those two fields is displaying should be required.

And, the requirement causing the problem:

  • If one required field is displaying, and then the picklist is changed again, the required field should both stop displaying and being required without any value having to be entered into it first.

Here is the picklist field with an actionSupport to rerender

<apex:inputField value="{!Case.Picklist__c}" required="True">
     <apex:actionSupport event="onchange" reRender="fieldBlock"/>
</apex:inputField>

And here is the pageblocksection with the conditionally required and rendered fields:

<apex:outputPanel id="fieldBlock">
    <apex:pageBlockSection>
         <apex:inputField value="{!Case.field1__c}" 
                          rendered="{!Case.Picklist__c=='Option 1'}"
                          required="{!Case.Picklist__c=='Option 1'}"/>
         <apex:inputField value="{!Case.field2__c}" 
                          rendered="{!Case.Picklist__c=='Option 2'}"
                          required="{!Case.Picklist__c=='Option 2'}"/>  
    </apex:pageBlockSection>
</apex:outputPanel>

Things I've tried from other posts on this topic:

  • Using immediate = true attribute on the actionSupport doesn't cause fieldBlock to rerender.
  • Using actionRegion tags doesn't seem to address the core issue that the region I want to rerender has required fields.

I believe one possible solution would be to remove the required attributes from the VF and instead use a controller method or javascript to validate the required fields. But before I turn to that I'd like to better understand why VF can't handle what I'm trying to accomplish: I've read that rerendering submits the entire page to the server, but shouldn't that not be an issue with my conditional logic for required fields?

Best Answer

When form contains mandatory fields immediate="true" will not work for ActionSupport.

Secondly, when form has mandatory fields, as per execution logic setters will fire first and then action methods are getting called. Though here you haven't used to call to controller. So, unfilled mandatory fields will restrict actionSupport to perform.

Recommendation:

1) If you want to use actionSupport then remove immediate=true and remove required=true for all the mandatory fields. You can perform validation at controller level.

2) If you really want to use required attribute then use actionFunction instead of actionSupport.

You can refer my answer of one of this kind of scenarios ReRendered form with wrong data on inputFields dependent picklist