I would use a4j
in order to render the inputText only if certain values of your selectOneMenu
are selected:
<h:selectOneMenu value="#{MyBean.selectedValue}">
<f:selectItems value="#{MyBean.listOfValues}" />
<a4j:support event="onchange" reRender="requiredText" ajaxSingle="true"/>
</h:selectOneMenu>
<a4j:outputPanel id="requiredText">
<h:inputText value="#{MyBean.inputValue}" rendered="#{(MyBean.selectedValue == value_1) || (MyBean.selectedValue == value_2) || ...}" />
</a4j:outputPanel>
In order to avoid a large string on inputText's rendered
parameter, I suggest you to create a boolean function which performs these conditions: rendered="#{MyBean.inputTextIsRendered}
.
CLIENT-SIDE SOLUTION
There's also a solution based on Validators. Here's my approach:
The selectOneMenu
code above uses the binding
tag to bind the value selected in the selectOneMenu
with an attribute that will be retrieved in the validator method, declared for the inputText
component.
Then, you need to create the CheckInputValue
validator class.
public class CheckInputValue implements Validator {
public CheckInputValue() {}
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
//We retrieve thei binded value:
UIInput confirmComponent = (UIInput) component.getAttributes().get("selectedValue");
String theValue = confirmComponent.getSubmittedValue();
//Here you check the retrieved value with the list of values that makes your inputText required.
//In these cases you will chech the inputText is not empty and, if so, you return a ValidatorException:
if(isEmpty){
FacesMessage message = new FacesMessage();
message.setDetail("inputText cannot be empty");
message.setSummary("inputText cannot be empty");
message.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message);
}
}
}
Finally, you have to declare your validator class in faces-config.xml
:
<validator>
<validator-id>CheckInputValue</validator-id>
<validator-class>myPackage.myValidations.CheckInputValue</validator-class>
</validator>