Question

I can't get a list obtained from a managed bean to show in a datatable in JSF.

When I debug it, the list has one element when it calls the method on the bean, but the page shows no elements in the datatable.

The managed bean is:

@ManagedBean
@ViewScoped
public class MyBeanMB {

    private List<MyBean> results = new ArrayList<MyBean>();
    private MyBean myBean = new MyBean();
    @EJB
    private MyBeanService myBeanService;

    public String findMyBeans() {
        results = myBeanService.findMyBeans(myBean);
        myBean = new myBeans();
        if (results != null && !results.isEmpty()) {
            return "success";
        }
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("No results found"));
        return null;
    }

And the form in index.xhtml page looks like this:

<h:form>
            <h:messages />
            <h:outputLabel value="Nombre: " for="nombre"/>
            <h:inputText id="nombre" value="#{myBeanMB.myBean.name}" />
            <h:commandButton value="Buscar" action="#{myBeanMB.findMyBeans}" />

            <h:dataTable id="list" value="#{myBeanMB.results}" var="item">
                <h:column>
                    <f:facet name="header">
                        <h:outputText value="Name"/>
                    </f:facet>
                    <h:outputText value= "#{item.name}" />
                </h:column>
            </h:dataTable>
        </h:form>

What am I missing?

Was it helpful?

Solution

When you return success in your managed bean, JSF will navigate to success.xhtml view (this assuming you haven't set a navigation rule in faces-config.xml file) and the list should be handled in this view, not in index.xhtml. In order to fix your code, change your findMyBeans method to return void instead of String.

public void findMyBeans() {
    results = myBeanService.findMyBeans(myBean);
    myBean = new myBeans();
    if (results != null && !results.isEmpty()) {
        return;
    }
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("No results found"));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top