Search code examples
jsfobjectpopulateselectonemenu

JSF selectOneMenu with Object iteration


I do know that similar problem was announced here few times but I spent a lot of time and still have no idea why that code doesn't work :/

This is my JSF page:

<h:form>
<h:selectOneMenu value="#{productBean.productName}">
    <f:selectItems value="#{productBean.products}" var="c" itemValue="#{c.name}"/>
</h:selectOneMenu>
</h:form>

This is my productBean:

public class ProductBean extends Connector
{
    private List<Product> products;
    private Product product;
    private String productName;
    //setters and getters
    public List<Product> getProducts() throws SQLException
    {
        resultSet = statement.executeQuery("SELECT * FROM dbo.products");
        products = new ArrayList<Product>();
        while(resultSet.next())
        {
            product = new Product();
            product.setId_product(resultSet.getInt("id_product"));
            product.setName(resultSet.getString("name"));
            product.setCategory(resultSet.getInt("category_id"));
            product.setIs_available(resultSet.getInt("is_available"));
            products.add(product);
        }
        return products;
    }
}

And finally product class:

public class Product 
{
    private int id_product;
    private String name;
    private int price;
    private int category;
    private int is_available;
    /setters and getters
}

My goal is to have a menu list with products names. All i got in the expanded list are references. I also tried to declare everything in the bean class and make ArrayList instead of ArrayList but i think it's not nice. It did't work anyway.

Tell me if I understand it corectly. productBean.productName is some kind of holder. productBean.products is a whole Products list and the c.name means that I want only name from the actual product.


Solution

  • You must also include the itemLabel :

    <f:selectItems value="#{productBean.products}" var="c" itemValue="#{c.name}" itemLabel="#{c.name}" />