Thanks to some great articles here, I've been able to build a <h:selectOneMenu />
with selectItems containing objects. After providing a custom FacesConverter and fixing the missing equals()/hashcode() methods, I am able to use it to change the property of the backing bean and write it out to the DB.
The only weird thing is that all HTML <option />
elements of the <select />
-element are checked="checked"
! In other words: the <h:selectOneMenu />
does not reflect the current value of the bound property!
Details:
Store.java
@Entity
public class Store {
private Long id;
private String name;
@ManyToOne
private Category category;
// getters, setters, equals, hashcode
}
Category.java
@Entity
public class Category {
private Long id;
private String name;
// getters, setters, equals, hashcode
}
editStore.xhtml
<h:form>
....
<h:selectOneMenu value="#{backingBean.store.category}" id="category">
<f:selectItems value="#{backingBean.categorySelectItems}" />
</h:selectOneMenu>
....
</h:form>
BackingBean.java
public class BackingBean {
private Store store;
// inject data-access-facades via @EJB
// Constructor
// getters, setters
public List<SelectItem> getCategorySelectItems
List<SelectItem> items = new ArrayList<SelectItem>();
for (Category cat : categoryFacade.findAll() ) {
items.add(new SelectItem(cat, cat.getName()));
}
return items;
}
// action methods
}
I leave out listing the Category-Converter (it converts between the object and its ID).
The HTML this creates is:
<select id="category" name="category" size="1">
<option value="251" selected="selected">Kosmetik</option>
<option value="222" selected="selected">Sportwaren</option>
</select>
Obviously, store.category
can only contain one item... why are both option-elements "selected"? No matter, what category is assigned to the store, the HTML always "selects" all option-elements.
How does JSF now, which SelectItem
should be selected?