How can I create toggle buttons in JSF?

How can I create toggle buttons in JSF?

Basically, I need two buttons "in" and "out". They essentially call the same managed bean, but each click must disable it and the other one must be enabled, and vice versa. How can this be done? Should I use the ajax function?

+3


source to share


1 answer


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:

+3


source







All Articles