How can I create toggle buttons in JSF?

耗尽温柔 提交于 2019-11-29 14:50:40
BalusC

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!