Search code examples
validationjsfjsf-2selectonemenuunique-values

Force user to select different values in multiple h:selectOneMenu showing same lists


I am relatively new to JSF and Primefaces. I have a page in which I have three selectOneMenu displaying the same set of values from a map. I would like to make sure that the user selects different values for the three drop downs. I have achieved this by writing a custom validator. But the validator works only if I click the submit page. I want to have an ajax call which would show an error message for drop down 2 as soon as the user selects the same value as drop down 1.Also the same case for drop down 3.Here is my code snippet:

user.xhtml

 <h:outputLabel  for="Question1" value="#{msg['account.question1']}"/>
   <h:message styleClass="validation-error" for="Question1"/>
<h:selectOneMenu id="Question1"  required="true" value="#{account.question1}" class="smallTxt">
        <f:selectItems value="#{controller.questionMap}" />
        <f:validator validatorId="com.validator.QuestionsValidator"></f:validator>
</h:selectOneMenu>

<h:outputLabel  for="Answer1" value="#{msg['account.answer1']}"/>
<h:message styleClass="validation-error" for="Answer1"/>
<h:inputText id="Answer1"  required="true"  value="#{account.answer1}" />

<h:outputLabel  for="Question2" value="#{msg['account.question2']}"/>
<h:message styleClass="validation-error" for="Question2"/>
<h:selectOneMenu id="Question2" required="true" value="#{account.question2}" class="smallTxt">
        <f:selectItems value="#{controller.questionMap}" />
</h:selectOneMenu>

<h:outputLabel  for="Answer2" value="#{msg['account.answer2']}"/>
<h:message styleClass="validation-error" for="Answer2"/>
<h:inputText id="Answer2" required="true" value="#{account.answer2}" />

<h:outputLabel  for="Question3" value="#{msg['account.question3']}"/>
<h:message styleClass="validation-error" for="Question3"/>
<h:selectOneMenu id="Question3" required="true" value="#{account.question3}" class="smallTxt">
    <f:selectItems value="#{controller.questionMap}" />
</h:selectOneMenu>

<h:outputLabel  for="Answer3" value="#{msg['account.answer3']}"/>
<h:message styleClass="validation-error" for="Answer3"/>
<h:inputText id="Answer3" required="true"  value="#{account.answer3}" />

I am using JSF 2 and Primefaces 5.2. Thanks in advance


Solution

  • If you want to execute your validator on an AJAX call, you have to add <f:ajax /> to your <h:selectOneMenu>

    <h:selectOneMenu id="Question1"  required="true" value="#{account.question1}" class="smallTxt">
        <f:selectItems value="#{controller.questionMap}" />
        <f:validator validatorId="com.validator.QuestionsValidator"></f:validator>
        <f:ajax />
    </h:selectOneMenu>
    

    Side question: You state, that you use Primefaces 5.2, but you use JSF standard components (<h:selectOneMenu> instead of <p:selectOneMenu>). Is that on purpose?