Friday, July 1, 2011

JSF2 state saving and event phase shifting

An annoying aspect of valueChangeListener in JSF2 is that it is not handled in the phase I expected.







The method selectAllChangeListener is in the validation phase and not in the invoke application phase as you may need it.
The good news is you can re-throw the event.

public void selectAllChangeListener(ValueChangeEvent e) {
if (!e.getPhaseId().equals(PhaseId.INVOKE_APPLICATION)) {
e.setPhaseId(PhaseId.INVOKE_APPLICATION);
e.queue();
} else {
boolean selectAll = (Boolean) e.getNewValue();
boolean lastSelectAllStateSet = (Boolean) getStateHelper().get(LAST_SELECTED_ALL_SET);
if (lastSelectAllStateSet != selectAll) {
getTableModel().setSelectAll(selectAll);
getStateHelper().put(LAST_SELECTED_ALL_SET, selectAll);
}
}
}

It is important to queue the event on the same component. Which is what e.queue() does. It is equivalent to

e.getComponent().queueEvent(e);


Another important point is the call to getStateHelper.
You cannot keep states in a JSF component. You will loose the reference to the component after a refresh of your page (F5 on Firefox). You must keep them with the getStateHelper method.

No comments:

Post a Comment