【问题标题】:How to add a condition in commandButton ( Primefaces)?如何在命令按钮(Primefaces)中添加条件?
【发布时间】:2013-12-25 13:52:22
【问题描述】:

我是 primefaces 框架的初学者,我希望我的 commandButton 验证所选项目是否为“全部”以调用特定方法 allBooks(),如果选择了另一个项目:调用另一个方法:loadBook()

<p:selectOneMenu value="#{bookBean.selectedBook.id}">
    <f:selectItem itemLabel="Select a book :" itemValue="" />
    <f:selectItem itemLabel="All" />
    <f:selectItems value="#{bookBean.selectedBooksItems}" />
    <p:ajax execute="bookSelect" event="change" listener="#{bookBean.loadBook}" />
</p:selectOneMenu>

<p:commandButton id="validate" action="#{bookBean.requestBook}" value="Validate"/>

【问题讨论】:

  • 这是业务逻辑;在你看来这样做是一种代码味道。它应该发生在您的支持 bean 中

标签: jsf primefaces commandbutton


【解决方案1】:

在您的 actionListener 方法中执行此操作

<p:selectOneMenu value="#{bookBean.selection}">
    <f:selectItem itemLabel="Select a book :" itemValue="#{null}" />
    <f:selectItem itemLabel="All" itemValue="#{'ALL'}" />
    <f:selectItems value="#{bookBean.options}" />
    <p:ajax/>
</p:selectOneMenu>

<p:commandButton actionListener="#{bookBean.loadButtonActionListener}" value="Load"/>

public void loadButtonActionListener(ActionEvent event){

    if(this.selection.equals("ALL")) {
        this.allBooks();
    } else {
        this.loadBook(this.selection);
    }

}

【讨论】:

  • @Angelika 使用我的命令按钮再试一次。也请用您的 bean 代码更新您的问题
【解决方案2】:

commandButton 默认为 ajaxified,因此这个 sn-p 可以按您的预期工作:

    <h:form>
        <p:selectOneMenu  value="#{myBean.selected}">
            <f:selectItem itemLabel="ALL" itemValue="ALL" />
            <f:selectItem itemLabel="NONE" itemValue="NONE" />

        </p:selectOneMenu>
        <p:commandButton value="Validate" actionListener="#{myBean.doAction}" />
    </h:form>

这里是声明的bean:

@Named
@RequestScoped
public class MyBean {

private String selected;

public MyBean() {
}

public String getSelected() {
    return selected;
}

public void setSelected(String selected) {
    this.selected = selected;
}

public void doAction() {
    if (selected.equals("ALL")) {
        System.out.println("ALL Called!");
    } else if (selected.equals("NONE")) {
        System.out.println("NONE Called");
    }
}
}

更新:

如果您想将 ajax 更改事件添加到 selectOneMenu,只需将此行嵌套在 selectOneMenu 元素中 &lt;p:ajax listener="#{myBean.doAction}" /&gt;

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 2020-06-10
    • 2015-10-19
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    相关资源
    最近更新 更多