3/18/2011

How to prevent bean fields from being overridden in JSF when using a ChangeListener

Maybe you had this problem before:


You have two input fields and a changeListener bound to one of them. If the changeListener fires, you also want to change the content of the second input field. It works, but sadly, JSF overwrites the values you just set with the initial values. 


Here is your solution: Push back the change event to a later phase in the JSF life cycle:



public final void someChangeListener(ValueChangeEvent event) {
PhaseId phaseId = event.getPhaseId();

if (phaseId.equals(PhaseId.ANY_PHASE)) {
event.setPhaseId(PhaseId.UPDATE_MODEL_VALUES);
event.queue();
} else if (phaseId.equals(PhaseId.UPDATE_MODEL_VALUES)) {
String newValue = (String) event.getNewValue();

setValue(newValue);
}

}

That´s all :)



If you like this tutorial it would be very nice, if you could click on some of the google ads you see on the right side. It helps me run this block and motivates me ;)

If you have any questions, feel free to leave a comment.