function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AbAb 

Customizing required and rendered components for inputField

Hello,

I have a custom object like below:
CustomObj__c
CustomField1__c (Picklist, values = Val1, Val2, val3)
CustomField2__c (lookup)

I want to control the display of the CustomField2__c depending on CustomField1__c

if(CustomField1__c = 'val1')
then CustomField2__c should be mandatory
else if (CustomField1__c = 'val2')
then CustomField2__c is hidden and should be not mandatory
else if (CustomField1__c = 'val3')
then the CustomField2__c is visible but not mandatory
<apex:inputField value="{!CustomObj__c.CustomField2__c }" required="{!logic1}" rendered="{logic2}"/>
thank you for suggestions !
Best Answer chosen by Ab
Shun KosakaShun Kosaka
Hi,
One way to realize dynamic/conditional required field is AJAX refreshes.
The following is an example of partial page refreshing.
<apex:form >
  <apex:pageblock>
  <apex:pageblocksection columns="1">
  	<apex:pageblocksectionItem >
  		<apex:actionRegion >
          	<apex:outputlabel value="Custom Field 1" for="customfield1" />
          	<apex:inputField value="{!CustomObj__c.CustomField1__c}" id="customfield1">
              	<apex:actionSupport event="onchange" reRender="myrefresh" />
          	</apex:inputField>
  		</apex:actionRegion>
  	</apex:pageblocksectionItem>
  
  <apex:outputpanel id="myrefresh">
  	<apex:pageblocksectionItem rendered="{!CustomObj__c.CustomField1__c != 'Val2'}">
      	<apex:outputlabel value="Custom Field 2" for="customfield2" />
      	<apex:inputField value="{!CustomObj__c.CustomField2__c}" required="{!CustomObj__c.CustomField1__c == 'Val1'}" id="customfield2"/>
  	</apex:pageblocksectionItem>
  </apex:outputPanel>
  
  <apex:commandButton action="{!save}" value="Save"/>
  
  </apex:pageblocksection>
  </apex:pageblock>
</apex:form>

See VF developer guide
- actionsupport tag : https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_compref_actionSupport.htm
- Using Ajax in a Page : https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_quick_start_ajax_partial_page_update_any_component.htm