More dynamic form with ValueListener
Next difficulty: I add a checkbox, and when the user check this box, I want some other fields to appear.
For now, only one input field will be enough, but this field, when displayed, must be filled by the user. It is mandatory.
How do you do that ?
Simply add the checkbox and the input, and map the rendered attribute of the input to the same model value of the checkbox.
1 2 3 4 5 6 7 8 9 10 11 | <ice:outputLabel value="Extended Search:" /> <ice:selectBooleanCheckbox id="extendedSearch" value="#{searchPage.extendedSearch}" /> <ice:outputLabel value="Extension:" rendered="#{searchPage.extendedSearch}"/> <s:decorate template="/layout/decorate.xhtml" rendered="#{searchPage.extendedSearch}"> <ice:inputText id="extension" value="#{searchPage.extension}" required="true"/> <ice:message for="extension" styleClass="message" errorClass="errormsg" infoClass="infomsg" warnClass="warnmsg"/> </s:decorate> |
The result should be, after a click in the check box:
But, nothing happens.
We have to tell JSF to generate an event as soon as the user click on the checkbox. By default, JSF does nothing.
We simply use our famous attribute partialSubmit= »true »
1 2 3 | <ice:selectBooleanCheckbox id="extendedSearch" value="#{searchPage.extendedSearch}" partialSubmit="true" /> |
Now, when we click on the checkbox, we have the dependant input field displayed or not. Great ! But we’re not done yet with this.
Let’s try to input an incorrect value in the integer field, then check the box:
Ooopps, the integer input just gets validated before the checkbox can modify the model value, so the dependant input field don’t display.
We need to set the immediate= »true » attribute:
1 2 3 | <ice:selectBooleanCheckbox id="extendedSearch" value="#{searchPage.extendedSearch}" immediate="true" partialSubmit="true" /> |
We must leave the partialSubmit= »true », otherwise no event occurs when clicking on the checkbox.
After testing, same (bad) result ! The validation error is displayed, but what’s annoying is that the checkbox is now checked, without the dependent input field displayed !
We need another trick: This trick, is to call a method when the value of the checkbox is changed. We do it like that:
1 2 3 4 | <ice:selectBooleanCheckbox id="extendedSearch" value="#{searchPage.extendedSearch}" immediate="true" partialSubmit="true" valueChangeListener="#{searchPage.extendedSearchChanged}" /> |
And the code for the called method is this:
1 2 3 4 5 6 7 8 9 | public void extendedSearchChanged (ValueChangeEvent evt) { // We set the value so that the // depedant fields are displayed or not setExtendedSearch((Boolean)evt.getNewValue()); // Using this, we bypass all validations // stuff, and redisplay directly the page. FacesContext.getCurrentInstance().renderResponse(); } |
And the result is just perfect! You can check / uncheck, you see the dependant input field disappearing or appearing accordingly, even if bad values are entered.







