4

How can I create toggle buttons in JSF?

Basically, I need two buttons "in" and "out". They essentially call the same managed bean, but as a result of every click the one should be disabled and the other should be enabled and vice versa. How can this be done? Should I use ajax functionality?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user489152
  • 907
  • 1
  • 23
  • 42

1 Answers1

6

Just have a boolean property which you inverse in action method and use exactly that property in the disabled attribute of the both buttons, inversed.

Kickoff example:

@ManagedBean
@ViewScoped
public class Bean {

    private boolean enabled;

    public void toggle() {
        enabled = !enabled;
    }

    public boolean isEnabled() {
        return enabled;
    }

}

With

<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 technically not necessary. Feel free to add <f:ajax> to both buttons to improve the user experience though.

A @ViewScoped bean is in turn very necessary. A @RequestScoped one would be trashed on end of request and recreated in next request, hereby causing the boolean to be reinitialized to default and thus seemingly fail to work after second click, because JSF will as part of safeguard against tampered/hacked requests also check the disabled (and rendered) attribute before actually invoking the action.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Hi BalusC, thanks for the answer. I used it in my code where the action toggle routine is also called by a selectOneMenu (i.e the button and the menu updated values decide my operation). In this case, the toggling fails. Any idea how this can be set? – user489152 Feb 06 '13 at 15:28
  • 1
    Hard to answer without seeing concrete code. Press `Ask Question` to ask a new question and put therein the code in SSCCE flavor. – BalusC Feb 06 '13 at 15:29