0

How do I dynamically set the required property on apex:inputField while using CSS to show/hide said field in order to avoid the validation error upon saving a form that has said field as hidden AND required?


I have a basic use case to Show/Hide an apex:inputField based on the selection of a value from a picklist. If the picklist is 'x' we show the field, if it is 'y' we hide the field.

The dependent field has to be required.

The issue is that when an apex:inputField is required, but the CSS for it is "display: none", the field is still run through the validation logic and an empty value prevents the form from saving.

I have tried to set the required attribute via JavaScript, and also via Apex using an apex variable and a rerender, but the rerender resets the CSS properties and the code becomes too circular for my liking.

Here is some code samples, this is a pretty concise version:

             <apex:inputField value="{!Product.Type}" required="true" id="producttype" onchange="setProductFieldJS(this.value);" /> 
      <apex:pageBlockSection id="targetFieldSection" columns="2">
                    <apex:pageBlockSectionItem id="targetFieldSectionItem">
                        <apex:outputLabel style="display:none" value="Target" For="targetField" />
                        <apex:inputField style="display:none" id="targetField" value="{!Product.Target}" required="true" />
                    </apex:pageBlockSectionItem>
                </apex:pageBlockSection>

            function setCostFieldJS(val) {
              if(val == 'X') {
                  $("[id$=targetField]").show();
              } else {
                  $("[id$=targetField]").hide();
              }
            }

I will underscore that I was trying to use the rerendered for the field as a whole, and while the render toggle functionality was working, a bug was preventing the field from saving at random times, so in lieu of spending more hours searching for the bug I am deferring to this hybrid method for now.

0

I think the following will work for you:

<apex:inputField style="display:none"
                 id="targetField"
                 value="{!Product.Target}" 
                 required={!IF(Product.Type == "X", true, false)}
/>

This should then only make the targetField required is Product.Type is "X" I haven't tested this. It was just my first thought. It might not re-evaluate on change...

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.