3

I have a small (but vital) problem with JSF and ajax. The form is here:

 <h:form>
        <h:panelGrid id="pg1" columns="2">

            <h:outputText value="Type: "/>

            <h:selectOneMenu id="selectOne" value="#{personBean.type}">
                <f:selectItems value="#{listBean.personTypes}"/>
                <f:ajax event="valueChange" render="pg2"/>
            </h:selectOneMenu> 

        </h:panelGrid>

        <h:panelGrid id="pg2" columns="2">

            <h:outputText value="Really bad?" rendered="#{personBean.type=='BAD'}"/>

            <h:selectBooleanCheckbox id="checkbox" value="#{personBean.reallyBad}" rendered="#{personBean.type=='BAD'}">
                <f:ajax event="click"/>
            </h:selectBooleanCheckbox>

        </h:panelGrid>

        <h:commandButton value="Ajax Submit" action="#{personBean.printValues}">
            <f:ajax execute="@form"/>
        </h:commandButton>
    </h:form>

The PersonBean is a simple bean with an enum PersonType that has two values: NICE, BAD and a Boolean called reallyBad. The ListBean returns the enum values in a list to populate the selectOneMenu.

Basically when I select BAD the panel for the boolean checkbox is rendered where I can tick it to say a person is reallyBad. I can then submit the form if I wish. The problem is when I tick the checkbox and then select NICE again, the checkbox is still ticked even though it is not rendered. So when I submit my form the person can be NICE and reallyBad, which doesn't make sense.

Rather than having to select BAD again to uncheck the box, is their a way that I can reset the checkbox and its input value to false when NICE is selected? I'm a bit of a noob to ajax with JSF! Thanks.

ps. I am printing the values of the two inputs on submit with the commandButtons action to verify the results...

Alan Smith
  • 1,069
  • 4
  • 19
  • 23

1 Answers1

1

You need to manually clear the checkbox when you change the menu.

<f:ajax listener="#{personBean.setReallyBad(false)}" render="pg2" />

By the way, the both <f:ajax event> values as you've in your code are the default values already. Just omit them.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks that worked! So on the checkbox I can just use and it will still work without the event value? Also, can I get your opinion on this... is it bad practice to have model type logic i.e. rendered="#{personBean.type=='BAD'}" in your view? I have been told elsewhere it is, mainly for debugging reasons. – Alan Smith Feb 26 '13 at 12:28
  • In `UIInput` components, the `event` attribute defaults to `valueChange` already which in turn would generate `click` in case of checkboxes. See also http://stackoverflow.com/questions/7886453/what-values-can-i-pass-to-the-event-attribute-of-the-fajax-tag/7889098#7889098 – BalusC Feb 26 '13 at 12:28