How can I create toggle buttons in JSF?
You just have a property boolean
that you invert in the action method and use that property in the attribute of disabled
both buttons, inverted.
Kickoff example:
@ManagedBean
@ViewScoped
public class Bean {
private boolean enabled;
public void toggle() {
enabled = !enabled;
}
public boolean isEnabled() {
return enabled;
}
}
FROM
<h:form>
<h:commandButton value="Enable" action="#{bean.toggle}" disabled="#{bean.enabled}" />
<h:commandButton value="Disable" action="#{bean.toggle}" disabled="#{not bean.enabled}" />
</h:form>
Ajax is not technically required. Feel free to add <f:ajax>
to both buttons to improve the user experience.
A @ViewScoped
bean, in turn, is very necessary. A @RequestScoped
could be destroyed at the end of the request and recreated in the next request, thereby boolean
being reinitialized by default and thus seemingly not working after the second click, because JSF would be as part of protecting against forged / hacked requests as well check the attribute disabled
(s rendered
) before invoking the action.
See also:
source to share