0

I'm a beginner in primefaces framework, I want that my commandButton verify if the selected item is "All" to call a specific method allBooks() , and if another item is choosen: to call another method : 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"/>
Kerem Baydoğan
  • 10,475
  • 1
  • 43
  • 50
Angelika
  • 381
  • 1
  • 9
  • 22
  • That's business logic; Doing it in your view is a code smell. It should happen in your backing bean – kolossus Dec 25 '13 at 21:27

2 Answers2

1

Do it in your actionListener method

<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);
    }

}
Kerem Baydoğan
  • 10,475
  • 1
  • 43
  • 50
0

commandButton ajaxified by default so this snippet work as you expect:

    <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>

here is declared 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");
    }
}
}

UPDATE:

if you want to add ajax change event to selectOneMenu just nest this line in selectOneMenu element <p:ajax listener="#{myBean.doAction}" />

Hamid Samani
  • 445
  • 5
  • 15